Friday, December 9, 2016

Rails: Validate only the fields that are within an array | Fixed issues

Rails: Validate only the fields that are within an array | Fixed issues


Rails: Validate only the fields that are within an array

Posted: 09 Dec 2016 08:09 AM PST

I am attempting to validate a model based on a serialized array stored in a separate model that it is referencing. If the user selects that option from a dropdown if will retrieve the serialized array from the other model. I have been able to get this to work, I just cannot seem to build a simple validator.

#controller  @parent = Parent.new(parent_params)  @parent.valid_fields = Child.find(@parent.sensor_id).fields  if @parent.valid?     ---  end    #model  def self.valid_fields=(val)     self[:valid_fields] = val  end  

I would like to validate it as long as the field is in the array. The fields range from simple strings to integers and decimals. I have been trying to build it in a manner such as this:

#model  validates :field_1, numericality: {message: "must be numeric" }, if: :validate_fields?, field: "field_1"  validates :field_2, numericality: { only_integer: true, message: "must be integer" }, if: :validate_fields?, field: "field_2"    def validate_fields?(*attr)     options = attr.pop if attr.last.is_a? Hash     If valid_fields.include?(options[:field])        true     else        false     end  end  

But so far I keep getting this error:

Unknown validator: 'FieldValidator'  

Thanks

Is it possible to use embedded ruby in tests?

Posted: 09 Dec 2016 07:55 AM PST

I used embedded Ruby in fixture to create n objects:

<% 30.times do |n| %>  micropost_<%= n %>:    content: <%= Faker::Lorem.sentence(5) %>    created_at: <%= 42.days.ago %>    user: michael  <% end %>  

Is it possible to use embedded Ruby in tests, in order to test the above n objects?
I would need to iterate over each object and make assertions as follows:

ActiveRecord::Base.connection.execute("TRUNCATE microposts")  (1..30).each do |num|    assert_nil micropost_<%= num %>  end  

Mongoid update column with unique token

Posted: 09 Dec 2016 07:30 AM PST

Let's take a look at the following code for ActiveRecord

def generate_token    update_column :token, SecureRandom.hex(3)  rescue ActiveRecord::RecordNotUnique    retry  end  

It enforces a unique token across the table. Therefore even with small codes (eg. only 5-6 letters) we can ensure uniqueness by retrying.

How do I achieve the same on Mongoid ?

Passing clientX and ClientY variables in Rails

Posted: 09 Dec 2016 07:40 AM PST

I'm working on a photo tagging project where a user clicks an area of the screen, a box appears around that area, and a they then select from a list of characters that they are supposed to find. At the moment, I can get the box and list of characters to appear using Jquery in my rails app. When the user clicks the name of the person they are guessing, it sends an ajax request to the server to check a few things out. This is where I run into trouble:

One thing I'm checking for is to see if the character falls inside of the box that was created on click. Each character has an X and Y coordinate attribute stored in the data base. My question is: How can I take the clientX and clientY information I gathered when the user clicks and use it to see if the XY coordinates in the data base match? I've included the most relevant code below. I know I should separate my js out of the view, but I plan to do that when I refactor.

Thanks for the help!

show.html.erb  <div id="containe">  <div id="tag-box"></div>  <div class="foo">      <span id="who">Who did you click?</span>      <% @users.each do |user| %>          <div class="user"><%= link_to user.username, users_check_path(:id => user.id), remote: true %></div>      <% end %>  </div>  <%= image_tag "/assets/waldo.jpg" %>  

<%= javascript_tag do %>      $(document).on("click","#containe",function(e){      var offset = $('#tag-box').offset({ top: e.clientY - 20, left: e.clientX - 40 }).show();      var form = offset.append($('.foo')).show();      yes = {x: e.clientX, y: e.clientY};      console.log(yes);      return yes;  });  <% end %>  

Activerecord or SQL - update each record with an incremented value with a single statement

Posted: 09 Dec 2016 08:03 AM PST

I have a cards table with an attribute called 'position', which has a default value of 0.

I need to select a group of cards, then assign the position of each card with an incremented value.

So, lets say that I select a group of cards using

cards = Card.where(id: [3,4,7,8]).   

Can a single Activerecord or SQL statement assign an incremented value, that would give a result like this?

cards[0].position   => 1  cards[1].position  => 2    ...  

How to test controller without hitting the database?

Posted: 09 Dec 2016 07:06 AM PST

I have a controller:

class InvoicesController < ApplicationController    def edit      @invoice = Invoice.includes(:client, :document_status).find(params[:id])      return head :forbidden unless @invoice.editable?    end  end  

I want to write a test but without hitting the database:

describe InvoicesController do    describe '#edit' do      let(:invoice_id) { '1' }      let(:invoice) { double(Invoice, editable?: false) }      let(:invoice_includes) { double }        before do        allow(invoice_includes).to receive(:find).with(invoice_id) { invoice }        allow(Invoice).to receive(:includes).with(:client, :document_status) { invoice_includes }      end        subject { get :edit, params: {id: invoice_id} }        it { is_expected.to have_http_status(403) }    end  end  

Is there a better approach? I don't like this chain of allows but I can't think of anything better. Setting the @invoice instance variable in the test would be bad, because then I would rely on the implementation.

I could obviously just create the invoice in the DB and don't bother about all the mocks and stubs. However, doing this in all the specs would slow down the whole test suite.

Simple Form bootstrap customize collection_radio_buttons field

Posted: 09 Dec 2016 07:18 AM PST

I have this collection_radio_buttons field which has been customized a bit to show icons, but now for some reason the error span tag is not showing anymore. Also i would like to get rid of the label wrapper around each input itself. Perhaps i would have to create a custom block in the initializers file? or maybe i am missing something in the block?

Here is my code

= f.simple_fields_for :answer_raiting do |builder|    = builder.collection_radio_buttons(:response, AnswerRaiting::RAITING, :first, :last,      collection_wrapper_tag: :div, collection_wrapper_class: "form-group radio-stars",      item_wrapper_tag: false) do |b|      = b.radio_button + fa_icon("star-o")  

Rails - What can cause a mouse cursor gap in textinput?

Posted: 09 Dec 2016 06:57 AM PST

I'am bit new in rails, and this is my first big project, so i'll try to make simple for avoid confusion.

I got a text input

<%= f.text_field :search_query, class: '', value: @value, id: "id" , autofocus: "true", onKeyUp: "fnctX(event);" do %>  

And, when I post, (press enter, click on button continue, press space for auto-completion), after the page is updating, the mouse cursor (carpet) is 2 chars away from the last word typed, like if it was padded with spaces.

However, the value of the text does not contain the unwanted spaces. I've tried all the stackov post like focus(); or setCursorPosition..., absolutely nothing works.

I'am completely lost for 2 days, ty for any clue.

gem install rails fails on nio4r windows7 ruby 2.3

Posted: 09 Dec 2016 07:15 AM PST

Trying to install rails on a windows 7 machine:

rubygems -v 2.5.2

ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

installed ruby

installed devkit

ruby dk.rb init  ruby dk.rb install   

Then> gem install rails (I'll get the following error)

Failed to build gem native extension windows 7

Traversing an array with special characters Ruby

Posted: 09 Dec 2016 06:38 AM PST

I am getting an array from ldap server... which is not syntactical correct.

[nil, [...], "01", "02", [...], "rt", [...]]  

is there any way to traverse or get useful values out of it..??

Thanks in advance

Editing my question for adding more info

app/models/user/ldap.rb

module User::Ldap      def user_level_test      foo =[]       @ul ||= ldap_levels.inject(nil) do |level, entry|        level = entry[:cn].first if entry[:member].include?(ldap_dn)          foo.push level      end      foo    end  

and then I am printing returned array in view and getting that weird array

Rails Cucumber Testing - Send form data to method

Posted: 09 Dec 2016 07:02 AM PST

I'm trying to send form data, from cucumber test, to controller method.

I have a form with login & password fields, and submit button.
The form View:

<%= text_field_tag 'login', id: 'login-input' %>  <%= password_field_tag 'password', nil, id: 'password-input' %>  <%= submit_tag 'Login', id: 'submit-credentials' %>  

In cucumber step, I input values in that form (login fields not shown, but similar).

Then(/^I press "password-input"$/) do    find("#password-input").click  end  Then(/^I enter "myPassword" into the "password-input"$/) do    find("#password-input").text("myPassword")  end  

So now login and password values are set.

I then press submit button

And(/^I press "submit-credentials"$/) do    find("#submit-credentials").click()  end  

And my authenticate method gets called as it should, but its parameters are empty.

When I input values normally on the webpage, everything works fine. Why doesn't the cucumber version work?

All my cucumber steps pass!! so im confused

How can I send data from textfields to controller method?

Thank you

Setting a variable with an alternative value if other options are blank

Posted: 09 Dec 2016 06:03 AM PST

I have a variable that must be set with a phone number, preferrably with a value from table A. If that's empty, it should be a value from table B (which is related to table A). If that's empty as well, it should be a value from another column on table B. Finally, if all of these are empty, it should be set to a string.

I tried to do this with ors:

telefone = a.telefone || a.associado_contato.first.telefone || a.associado_contato.first.celular || "não cadastrado"   

But the result is a.telefone (the first option) even if it's blank.

I wanted to avoid nested ifs. Is there a simple solution to this situation?

How to add/implement SendGrid if the app is not deployed/hosted on Heroku?

Posted: 09 Dec 2016 05:48 AM PST

When the app is deployed on Heroku, the command to add/implement SendGrid is:

heroku addons:create sendgrid:starter

I am planning to deploy my next rails app on a DigitalOcean/Nginx/Passenger/Capistrano setup. My question is, how do I add/implement SendGrid to my app now?

Controller test with RSPEC and FactoryGirl fails with error expected: 1 got: 0

Posted: 09 Dec 2016 06:01 AM PST

The model Organization has many Events and and Event always belongs to an Organization.

My Events controller test, the file controllers/events_controller_spec.rb is:

require 'rails_helper'    RSpec.describe EventsController, type: :controller do      describe "POST #create" do      context "with valid attributes" do        it "create new event" do          post :create, event: attributes_for(:event)          expect(Event.count).to eq(1)        end      end      end  end  

This is my factories/organizations.rb file:

FactoryGirl.define do    factory :organization do      organization_name { Faker::Company.name }    end      factory :invalid_organization, class: Organization do      organization_name ''    end  end  

This is my factories/events.rbfile:

FactoryGirl.define do    factory :event do      event_description { Faker::Lorem.sentence(3) }      host_name { Faker::Internet.domain_name }      organization { create(:organization) }    end  end  

Based on the above I am assuming that an organization is created before any event is created.

My test is failing with this error.

$ rspec spec/controllers/events_controller_spec.rb    Failures:      1) EventsController POST #create with valid attributes create new event       Failure/Error: expect(Event.count).to eq(1)           expected: 1              got: 0           (compared using ==)       # ./spec/controllers/events_controller_spec.rb:9:in `block (4 levels) in <top (required)>'    Finished in 1.53 seconds (files took 9.03 seconds to load)  1 example, 1 failure  

Don't know how to fix it and have the test passed?

filepicker_rails re-bind new filepicker_field elements

Posted: 09 Dec 2016 05:40 AM PST

I'm using Filepicker in a Rails project via the filepicker_rails gem.

Everything works fine, but with this particular UI, there are cases where I need to dynamically add new filepicker_field buttons (the button that allows you to upload a new image). However, these newly added buttons do not work; they do not open the Filepicker dialog modal when clicked; best as I can tell, they do nothing.

I'm not sure what the issue here is, but I'm guess these new elements need to be rebound to the filepicker js, but I do not know how this can be achieved with the gem.

Any thoughts would be appreciated.

Separating posts in a newsfeed using CSS/BootStrap

Posted: 09 Dec 2016 07:01 AM PST

I'm currently trying to render a newsfeed, similar to that of FB on a Rails application I'm working on. Unfortunately, I'm not the greatest when it comes to CSS and I'm having some issues trying to display different posts. This issue occurs whether I'm using BootStrap or plain CSS. I do believe it's something to do with the loop that is created by <% @posts.each do |post| %> Currently, whenever a new post is made, it wraps inside the previous post; thus the more posts that are made, the thicker the border gets.

Image: Newsfeed

<% if @posts.any? %>  <% @posts.each do |post| %>  <div class="well">    <a href="/users/<%= post.user.id %>/show"><%= post.user.first_name %> <%= post.user.last_name %></a><br>    <% if !post.image.exists? %>      <h2> <%= post.text %> </h2>    <% else %>      <h2> <%= link_to post.text, post_path(post) %> </h2>      <%= link_to post_path(post) do %>        <p><%= image_tag post.image.url(:medium) %></p>      <% end %>    <% end %>  <% if @user %>      <% if current_user.voted_up_on?(post) %>        <%= link_to "Like", dislike_post_path(post), method: :put %>      <% else %>        <%= link_to "Like", like_post_path(post), method: :put %>      <% end %>  <% end %>  <%= "Likes: #{post.get_upvotes.size}" %>  <% if post.user == current_user %>  <%= link_to "Edit", edit_post_path(post) %>  <%= link_to "Delete", post_path(post), method: :delete %>  <% end %>  <div id='comments_div' class="comments-index">    <%= render post.comments %>  </div>  <% if current_user %>    <%= form_for [post, post.comments.new ], remote: true do |f| %>     <%= f.text_area :text, placeholder: 'Add a comment' %>     <%= f.submit 'Comment' %>    <% end %>  <% else%>    <p>You need to <%= link_to "sign in", new_user_session_path %> to comment</p>  <% end %>  <% end %>  <% else %>  No posts have been added!  <% end %>  </div>  

Any help would be greatly appreciated! Thanks.

Edit: OK, please take a look at the new image -- hopefully that will make the issue slightly more obvious. Additionally, I've removed all the dead tags and replaced them with just one: BootStrap's 'well' class. So, there you have it. All the information you need is within the code above.

Rails: How can I load new values into a form on edit but only persist them on save?

Posted: 09 Dec 2016 06:11 AM PST

I've got a Rails 4 app with a service that loads required objects on a new/edit document action, and this is a method from it:

def template_variables    if @document.template_variables.any?      TemplateVariable.where(id: document_vars).each do |v|        next unless User.method_defined?(v.name.to_sym)        v.update_attribute(:text, @user.send(v.name.to_sym)) # problem line, persists the change when i don't want to        v.text = @user.send(v.name.to_sym) # also a problem, doesn't update the value in the form at all      end    else      TemplateVariable.where(id: master_vars)    end  end  

I need a solution for the two problem lines (they are just two things I've thought of, and they aren't supposed to both be there but I've included both for the sake of my problem).

The first updates and persists the change to the model which is behaviour I don't want. The second line doesn't do anything, where logically it seems like it should replace whatever text was in that variable in the form with @user.send(v.name.to_sym). It appears to do nothing.

Is there are solution to this problem that I'm unaware of?

Bonus points if there's a way to list the fields with new values to display in a flash[:notice].

Update now with relevant form code.

<%= v.input :text, as: :string, input_html: { value: v.object.text } %>  

Setting the value/vs not setting it doesn't change anything either.

Ruby - Accessing parent application title from an engine

Posted: 09 Dec 2016 05:21 AM PST

I'm creating an engine which pulls a copy of the parent app's SQL database.

I'm trying to create a method which reads the title of the parent app to use in the title - what is the easiest way to do this?

Most times I've seen this question asked the answers seem to advise that this isn't best practice, if that is the case then how should I go about getting what I need?

Thanks.

icon as the main button in rails form

Posted: 09 Dec 2016 05:25 AM PST

My problem is quite simple. I just want the icon to be the button. No borders. I've tried button_to but somehow it produces the icon inside the button. I've also tried link_to and it looks good but then this is gonna be used to submit a form. It's quite simple but somehow I can't get the behavior that i want.

Here are my attempts at this:

= button_tag(type: 'submit') do    i class="fa fa-arrow-right arrow-enter"    = f.submit "", class: 'fa fa-arrow-right arrow-enter',id: 'user_sign_form_submit'    = link_to "", some_path(), class: 'fa fa-arrow-right arrow-enter'  

Thanks in advance!

Ability for users to sign up via SMS (Rails)

Posted: 09 Dec 2016 05:29 AM PST

I am working on a rails application where the main user model is authenticable by mobile number and a password. This all works fine through the website.

What I would like to do is enable a user to access all the same functions of the web app using solely an old school cell phone - that is purely via SMS. I have already enabled some of the web app functions via SMS using Twilio but I was unsure how to go about handling the creation of a user password via SMS in a secure manner.

What I would like:

  1. User sends the word "LOAN" to our Twilio number.
  2. This creates an account on our system based on their mobile_number. However, a password is required in order to persist a user in the DB so this will need to also be generated here.
  3. An SMS is sent to the user with their password in a secure manner.

I imagine my TwilioController action will look something like this:

def sign_up    if params["Body"] == "LOAN"      user = User.create(mobile_number: params["From"], password: __?__)      user.sms_sign_up # method to send the sms to the user    else      send_failure_sms(params["From"])    end  end  

I am already familiar with how to set this up on my Twilio account using TwiML apps - I am only interested in understanding how to manage the password aspect of this problem! Thanks

EDIT: I have seen that Devise provides the method #friendly_token. Is this something that would be useful in this case?

rails rspec capybara select not working

Posted: 09 Dec 2016 07:49 AM PST

In my rails app, I have a select on the navigation bar as follows:

<body>    <div id="wrapper">      <!-- Navigation -->    <nav role="navigation" style="margin-bottom: 0">      <div class="navbar-default sidebar hidden-sm hidden-xs" role="navigation">        <div class="sidebar-nav">          <ul class="nav" id="side-menu">            <li>              <h4 class="sidebar-title">SGPLAN</h4>            </li>            <li class="logo">              <form action="#">                <select name="" id="change_plan" class="form-control plan">                  <option value="1" id="plan_id" selected="">first </option>                  <option value="2" id="plan_id">other </option>                </select>              </form>            </li>  

and javascript in application.js to load the home page when the user selects a different option.

$(document).ready(function() {      //...      $('#change_plan').on('change', function(){          var str = ''          str += $( this ).val() + " ";          setCookie("plan", str,1);          window.location.href = "/";      })  });  

I have written the following test for this feature using rspec, capybara and capybara-webkit:

require 'rails_helper'    feature "Change plan", :js do    background do      login_as create(:admin_user), scope: :user      Agency.current = Agency.find_by(initials: 'SECTI').id      FactoryGirl.create(:other_plan)      Plan.current = Plan.find_by(name: 'first').id    end      scenario "User changes the current plan" do      visit "/milestones"      save_and_open_page      select('other', from: 'change_plan')      # within '#change_plan' do      #   find("option[value='2']").click      # end      # find('#change_plan').find('option', text: 'other').select_option      expect(current_path).to eq("/")    end  end  

save_and_open_page results in the html snippet as shown above.

The result of running the test is as follows:

Failures:      1) Change plan User changes the current plan       Failure/Error: expect(current_path).to eq("/")           expected: "/"              got: "/milestones"           (compared using ==)       # ./spec/features/plans/change_plan_spec.rb:19:in `block (2 levels) in <top (required)>'    Finished in 1 minute 1.71 seconds (files took 2.04 seconds to load)  1 example, 1 failure  

If I use find('#change_plan')... or find("option...") (as per the commented out lines) in the test instead of the select, the result is the same.

My versions are follows (from Gemfile.lock):

capybara (2.7.1)  capybara-webkit (1.11.1)  database_cleaner (1.5.3)  factory_girl_rails (4.7.0)  rails (4.2.5)  rspec-core (3.5.4)  rspec-expectations (3.5.0)  rspec-mocks (3.5.0)  rspec-rails (3.5.2)  

and ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

What do I need to do get this test to work? Should I be using a different test platform? We are relatively committed to rspec but less so to capybara.

Rails POST to Google Calender API via rest-client gives 'bad request' error

Posted: 09 Dec 2016 04:36 AM PST

I've searched many other questions and I don't see that I'm doing anything different, but rest-client will not work when trying to post a new event to Google API

url = "https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token=#{token}"  params = {start: 'test'}.to_json  response = RestClient.post url, params    RestClient::BadRequest (400 Bad Request)  

HTML JavaScript hide/show button

Posted: 09 Dec 2016 05:08 AM PST

I'm working on a little Ruby on Rails application and I'm trying to add a hide/show button which hides a div with some Id. I've followed the steps from this post and it hides the content (second answer). The problem is that the content is not hidden permanently. Once I click in the button, the content dissapears, then the browser do something like an auto refresh and the content appears again.

Could anyone help me with this? It is my first application and my background in javascript is quite poor...

A piece of the code I want to hide/show is the following:

<div id='test'>    <div class="col_4 patients-list">      <!-- Patients list -->      <h5>Patients en cours: <%= @patients.size %></h5>      <div>        <% @patients_anomaly.each do |patient| %>          <div class="patient-anomaly"><%= link_to_patient patient %></div>        <% end %>        <% (@patients_to_exit - @patients_anomaly).each do |patient| %>          <div class="patient-to-exit"><%= link_to_patient patient %></div>        <% end %>        <% @patients_normal.each do |patient| %>          <div class="patient-normal"><%= link_to_patient patient %></div>        <% end %>      </div>    </div>  </div>  <button>Click</button>  

and the javascript of the button is:

<script type="text/javascript">    $("button").click(function() {      $("#test").toggle('hide');    });  </script>  

Thank you in advance.

Rails - Group by 2 date columns

Posted: 09 Dec 2016 04:28 AM PST

Using Rails and PostgreSQL how can I group by two DATETIME columns?

I want to format a string based on the weekdays of a establishment is open

Eg: MON-FRI 10:00 - 22:00, SAT-SUN 10:00 - 18:00

I have this model

# == Schema Information  #  # Table name: establishment_open_hours  #  #  id                  :integer          not null, primary key  #  weekday             :string  #  opens_at            :datetime  #  closes_at           :datetime  #  openable_hours_id   :integer  #  openable_hours_type :string  #  created_at          :datetime  #  updated_at          :datetime  #    class Establishment::OpenHour < ActiveRecord::Base    belongs_to :openable_hours, polymorphic: true  end  

nginx: use different server for different path

Posted: 09 Dec 2016 05:16 AM PST

I have two Rails applications sitting behind two different URIs on the same machine. The nginx configuration is for each application in an own configuration file.

Now one of the applications has to be slowly merged into the second one. There is an endpoint accessible under the URI path application-one.com/register. I want only this application-one.com/register path to be accessing the second application and all other paths (application-one.com/* except /register) still accessing the first application.

Is there a way to do this without using 301 Redirects since I am not able to use them in my case?

An example configuration file looks like this:

upstream unicorn_application_one {      server unix:/tmp/unicorn_application_one.sock fail_timeout=0;  }    server {      client_max_body_size ....      ...      server_name application-one.com        root /home/deployer/application_one/current/public;      try_files $uri/index.html $uri @unicorn_application_one;        location @unicorn_application_one {          proxy_set_header ...          ....      }        location ^~ /assets/ {          ...      }        ....  }  

How to use exists filter in an aggregation for elasticsearch in ruby

Posted: 09 Dec 2016 03:30 AM PST

I am using elasticsearch-ruby gems, and I am trying to get the number of retweet in an aggregation. I am using the following DSL query:

search{}.aggregation('retweet') { filter {exists field: 'retweeted_status.id' }}  

So I try to use the 'exists' query ( https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-exists-query.html )but it seems that exists filter can not be used in this contex, I got the result:

NoMethodError: undefined method 'exists' for #<Elasticsearch::DSL::Search::Aggregations::Filter:0x007fe4fbe33ae0>  

Issue regarding parsing a file in ruby on rails

Posted: 09 Dec 2016 05:50 AM PST

I have a text file (.txt) which contains an array and the elements of these array is in string format but these are also arrays. Just like the following:

For example, lets consider my file as:

["[1, 2016-11-18 07:38:26 +0000, \"ho\"]","[1, 2016-11-18 07:38:29 +0000, \"hose cla\"]", "[1, 2016-11-18 08:24:54 +0000, \"mo\"]"]  

Now I want to parse these file and I need to print the data in the following format as:

1   2016-11-18 07:38:26 +0000   ho    1   2016-11-18 07:38:29 +0000   hose    1   2016-11-18 08:24:54 +0000   mo  

Now , I just don't know where to start. I know how to parse a text file in ruby but this time its containing an array. So I am confused how to start and did not get the right idea yet.

Please help me by giving me some hints.

Thanks in advance!!!

I am using the following code to store the content of the file into the array. But it is not giving me the proper format. My file contains array in a contiguous manner. There is no new line in it. I think it causing the problem in the following code.

arr=[]    arr=File.foreach('input.txt').map { |line| line.split(' ') }  

What will be the RSpec test case for devise invitation controllers edit and update method

Posted: 09 Dec 2016 04:18 AM PST

I am not able to go in my invitation controller edit method, I have tried everything but not able to go in edit method.

Here is my edit method test case:

describe "GET :edit invitation" do      it 'should edit invitation' do          new_user = FactoryGirl.create(:user, invited_by_id: @user.id)          raw, enc = Devise.token_generator.generate(new_user.class, :invitation_token)          new_user.invitation_token = enc          new_user.save          new_user.invite!          # new_user = User.invite!({:email => new_user.email}, controller.current_user)          get :edit, { invitation_token: enc }      end  end  

How to connect one model to another more than once?

Posted: 09 Dec 2016 03:41 AM PST

I have quite a specific problem so I'll translate it into more understandable and clear example.

So we have 'Country' and 'Image' models. A Country has its flag and its arm.

This means we have to connect Country to Image 2 times. I tried transforming Rails guide's recipe 'Connecting to itself', however, I always get an exception: "Image expected, got String".

*Country model     class Country < ApplicationRecord       has_one :flag, class_name: 'Image', foreign_key: 'id'       has_one :arm,  class_name: 'Image', foreign_key: 'id'     end    *Image model     class Image < ApplicationRecord       belongs_to :flag, class_name: 'Country'       belongs_to :arm, class_name: 'Country'     end  

Rails; sum total

Posted: 09 Dec 2016 04:05 AM PST

I'd love to refactor the code below in more like Ruby way.

def cal_total      total = nil      items.each do |item|        total = total + item.itemable.amount      end      total  end  

Basically just iterate object, fetch the each amount, and return the total. Any idea?

update

total = item.itemable.amount is correct.

No comments:

Post a Comment