无法使用has_one关联获取嵌套表单 [英] Cannot get nested form with a has_one association to work
问题描述
我有以下模型:
class User < ActiveRecord::Base
has_one :city
accepts_nested_attributes_for :city
end
class City < ActiveRecord::Base
belongs_to :user
end
此控制器操作:
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
和此视图:
<%= form_for :user,:url => users_path,:method => :post do |f| %>
<%= f.fields_for :city do |b| %>
<%= b.collection_select :id,City.all,:id,:name %>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我正试图允许用户从已添加的城市列表中选择一个城市.我正在尝试给他一个选择.选择部分可以正常工作,但是为其生成的html代码如下所示:
I am trying to allow the user to select a city from the list of already added cities. I am trying to present him a select. The select part it works, but the generated html code for it, looks like this:
<select name="user[city][id]" id="user_city_id">
<option value="1">One</option>
<option value="2">Two</option>
</select>
请注意,它的名称在任何地方都没有attribute
.因此,当我尝试保存它时,出现此错误:
Notice that it's name doesn't have attribute
anywhere. So, when I try to save it, I get this error:
City(#37815120) expected, got ActiveSupport::HashWithIndifferentAccess(#32969916)
我该如何解决?
有一些进展,我试图将fields_for更改为此:
there is some progress, I tried to change the fields_for to this:
<%= f.fields_for :city_attributes do |b| %>
<%= b.collection_select :id,City.all,:id,:name %>
<% end %>
现在,html似乎可以正确生成.但是我现在收到此错误:
and now, the html seems to generate correctly. But I get this error now:
Couldn't find City with ID=1 for User with ID=
我不知道下一步该怎么做.
I have no idea what to do next.
覆盖city_attributes=
方法似乎有效:
def city_attributes=(attribs)
self.city = City.find(attribs[:id])
end
我不知道这是不是要走的路,但这似乎很好.
I don't know if it's the way to go, but it seems good.
推荐答案
看看这个与您的问题相似的问题: 第3条:"accepts_nested_attributes_for"如何实现?工作吗?
Have a look at this question that seems similar to yours : Rails 3: How does "accepts_nested_attributes_for" work?
实际上,由于城市已经存在,我认为这里不需要嵌套表格.
Actually, since the Cities already exsit, I think there is no need for nested forms here.
尝试更换
<%= f.fields_for :city_attributes do |b| %>
<%= b.collection_select :id,City.all,:id,:name %>
<% end %>
使用
<%= f.collection_select :city, City.all,:id,:name %>
评论后更新
您可以更改与您的关系(并相应地更新数据库方案)
Could you change your relationship with (and update database scheme accordingly)
class User < ActiveRecord::Base
belongs_to :city
end
class City < ActiveRecord::Base
has_many :users
end
然后尝试使用:
<%= f.collection_select :city_id, City.all,:id,:name %>
这篇关于无法使用has_one关联获取嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!