我正试图在一个accepts_nested_attributes_for关联模型上使用has_one,但却一无所获:-
我有两个型号,一个用户和一个位置。用户有一个位置:
class User < ActiveRecord::Base
# current location
has_one :location, :dependent => :destroy
accepts_nested_attributes_for :location
end
class Location < ActiveRecord::Base
belongs_to :user
end
我可以通过从控制台使用User.find(1).location.current_location_text = "blah"
保存对模型的更改,因此我知道关联的设置是正确的。
我在编辑用户页面上有两个表单。一个更新主用户属性(并且工作正常,下面没有显示),然后这个属性允许用户更新位置模型的属性,称为"current_location_text":
<%= form_for(@user) do |f| %>
<%= fields_for(@user.location) do |location_fields| %>
<%= location_fields.label :current_location_text, 'Current Location' %>
<%= location_fields.text_field :current_location_text, :placeholder => 'Road, City or Postcode' %>
<% end %>
<%= f.submit "Update Current Location" %>
<% end %>
这不管用。我有点困惑,因为表单发送的参数看起来不正确。当提交表单时,它在日志中显示:
Started PUT "/users/1" for 127.0.0.1 at 2011-10-08 00:28:05 +0100
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"YdTAsXwEvRgXIqri+jfx3dLlYG2XWQTuYkgLDsO/OJw=", "location"=>{"current_location_text"=>"E14 8JS"}, "commit"=>"Update Current Location", "id"=>"1"}
User Load (10.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
User Load (5.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1 [["id", "1"]]
SQL (4.4ms) BEGIN
(2.5ms) COMMIT
Redirected to http://localhost:3000/users/1
有两件事我觉得很奇怪:
,
{"utf8"=>"✓“、”utf8“8JS"}、”提交“=>”更新当前位置、“id”“=>”1“}}
我不认为我在这里是完全愚蠢的。我错过了什么很明显的东西吗?我尝试在表单中添加额外的隐藏字段(即用户id ),然后得到用户哈希,但与“位置”哈希的级别相同,而不是像我所期望的那样作为它的父级!
此外,如果有帮助,下面是我在UsersController中的更新:
def update @user = User.find(params:id)
if @user.update_attributes(params[:user])
redirect_to current_user, :notice => 'User was successfully updated.'
else
render :action => "edit"
end
结束
下面是我的routes.rb中的内容(尽管我不认为它与此相关):
resources :users do
resource :location
end
任何帮助都很感激。如果我不解决这个问题,笔记本电脑就会从窗户出去.谢谢。
发布于 2011-10-07 17:52:00
<%= fields_for(@user.location) do |location_fields| %>
这是你的问题。实际上,您需要在表单中“嵌套”fields_for,如下所示:
<% f.fields_for(@user.location) do |location_fields| -%>
发布于 2011-10-07 17:47:56
试一试这个
<%= f.fields_for :location do |location_fields| %>
与其将对象本身赋予它,不如告诉rails您希望加载它的关联。
https://stackoverflow.com/questions/7693929
复制