我有用户注册表格。用户必须通过选择选项来选择他的国家。当我提交表单时,我收到错误 Country(#70309119520500) 预期,得到 String(#8039220)
请帮助我如何将字符串转换为整数,以便我可以在数据库中插入记录。

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

这是我的 html.rb 表单
<%= 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 %>

这是请求
    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"=>"[email protected]",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"},
 "commit"=>"Create Account"}

用户 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

最佳答案

假设您的 User 模型是 belongs_to :country ,您会希望表单提交 country_id ,而不是 country 。尝试类似:

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

您还需要允许 country_id 作为 Controller 中的属性。

关于ruby-on-rails - Rails 4 : f. 选择返回字符串而不是整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27082579/

10-15 20:35