Rails 4:f.select返回的字符串不是整数 [英] Rails 4: f.select returns string not integer
问题描述
我有用于用户注册的表格.用户必须通过选择选项来选择他的国家.当我提交表单时,我得到预期的错误国家(#70309119520500),得到了字符串(#8039220) 请帮助我如何将字符串转换为整数,以便我可以在数据库中插入记录.
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
这是我的html.rb表单
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 %>
这是请求
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
推荐答案
假设您的用户模型belongs_to :country
,您将希望表单提交country_id
,而不是country
.尝试类似的东西:
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 %>
您还需要在控制器中允许country_id
作为属性.
You'll need to permit country_id
as an attribute in your controller too.
这篇关于Rails 4:f.select返回的字符串不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!