我试图在 has_one 关联模型上使用 Accepts_nested_attributes_for ,但绝对无处可去:-(
我有两个模型,一个用户和一个位置。一位用户有一个位置:
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
我觉得这件事有两件事很奇怪:
有“COMMIT”消息,但前面没有更新字符串,也没有错误。例如,如果您尝试提交受保护的属性,此时您会收到“您无法批量分配...”错误消息。
-
我觉得参数不对。 “位置”位按照我的预期嵌套,但我也希望它嵌套在“用户”哈希中,如下所示:
{"utf8"=>"✓", "authenticity_token"=>"YdTAsXwEvRgXIqri+jfx3dLlYG2XWQTuYkgLDsO/OJw=", "user"=>{"location"=>{"current_location_text"=>"E14 8JS"}, "commit"=>"Update Current Location", "id"=>"1"}}
我不认为我在这里完全愚蠢。我是否遗漏了一些非常明显的东西?我尝试在表单中添加额外的隐藏字段,即用户 ID,然后获取用户哈希,但与“位置”哈希处于同一级别,而不是像我期望的那样作为它的父级!
另外,如果有帮助,这是我在 UsersController 中的更新:
默认更新
@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
end
这是我的 paths.rb 中的内容(尽管我认为它不相关):
resources :users do
resource :location
end
任何帮助表示赞赏。如果我不解决这个问题,笔记本电脑就会被扔出窗外......
谢谢。