我有用户注册表。用户必须通过选择选项选择他的国家/地区。当我提交表格我得到错误国家(#70309119520500)预期,得到字符串(#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"=>"myEmail@gmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"commit"=>"Create Account"}
用户控制器
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
答案 0 :(得分:1)
在create
方法中,您应该能够快速将:country param转换为如下整数:
@user = User.new(user_params.tap{ |u| u[:country] = u[:country].to_i })
答案 1 :(得分:1)
假设您的用户模型belongs_to :country
,您希望表单提交country_id
,而不是country
。尝试类似:
<%= f.select :country_id, options %>
您还需要在控制器中允许country_id
作为属性。