Rails 4: f.select returns string not integer

橙三吉。 提交于 2020-01-04 04:37:11

问题


I have form for user registration. User has to select his country via select options. When i submit form i get error Country(#70309119520500) expected, got String(#8039220) Help me please how to convert string to integer so i can insert record in database.

ruby -v: ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]
rails -v: Rails 4.1.8

This is my html.rb form

<%= form_for :user, url: users_path do |f| %>
    <div class="field">
      <%= f.label :countries %>
      <% options = options_from_collection_for_select(Country.all, 'id', 'country', 1) %>
      <%=  f.select :country,  options %>
    </div>
<% end %>

This is request

    Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"34/KncZpwhEDYRZuWe09nKmF7DG7+lEu0IBxe9YbKnE=",
 "user"=>{"firm"=>"Chillum doo",
 "name"=>"myname",
 "last_name"=>"mylastname",
 "address"=>"myAdress",
 "post_number"=>"0000",
 "city"=>"myCity",
 "country"=>"1",
 "telephone"=>"000000000",
 "mobile_phone"=>"000000000",
 "user_name"=>"myUserName",
 "email"=>"myEmail@gmail.com",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"},
 "commit"=>"Create Account"}

Users controller

class UsersController < ApplicationController


  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save!
      redirect_to '/', notice: 'User registered successfully'
    else
      render 'new'
    end
  end

  private
  def user_params
    params.require(:user).permit(:firm, :name, :last_name, :address, :post_number,
                                 :city, :country, :telephone, :mobile_phone, :user_name,
                                 :email, :password, :password_confirmation)
  end

end

回答1:


Presuming that your User model belongs_to :country, you'll want your form to submit the country_id, not the country. Try something like:

<%=  f.select :country_id,  options %>

You'll need to permit country_id as an attribute in your controller too.




回答2:


In your create method, you should be able to quickly turn the :country param to an integer like so: @user = User.new(user_params.tap{ |u| u[:country] = u[:country].to_i })



来源:https://stackoverflow.com/questions/27082579/rails-4-f-select-returns-string-not-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!