0

试图执行嵌套对象形式。页面加载没有错误,但是当我发送它时,没有信息被保存到组织模型中。

SQL调用说这个..

Parameters: {"commit" => "save", "action"=>"update","_method"=>"put",  "organization"=>{"likes_snacks"=>"0"}, ..

哪个是对的。通过打开和关闭复选框可以正确更改 1 和 0。但是我猜这些信息并没有保存到数据库中。有任何想法吗?

哈姆勒:

- form_for @user do |f|
  = f.label :username
  = f.text_field :username
.clear
  - fields_for :organization do |org| unless @user.organizations.empty?
    = org.label :likes_snacks, 'Like snacks?'
    = org.check_box :likes_snacks
= f.submit 'save', {class => 'button'}

控制器:

def edit
  @user = current_user
  @organization = current_user.organizations.first
end

楷模:

组织.RB:

has_many  :users, :through => :organizations_users

用户.RB:

has_many  :organizations, :through => :organizations_users
4

3 回答 3

2

似乎您可以保存父属性但不能保存子属性。

要使子属性可以通过嵌套表单访问,您需要将“#{child_class_name}_attributes”添加到父类的 attr_accessible 方法中。(仅attr_accessible在父模型中使用时)

所以你的父模型应该是这样的:

class User < ActiveRecord::Base
  attr_accessible :username, :organizations_attributes
  accepts_nested_attributes_for :organizations
end

此外,如果您不在attr_accessible父模型中使用,则没有必要。

于 2010-07-19T17:27:53.260 回答
1

我认为这里有趣的部分是链接器表:organization_users。

关于这个问题的公认答案说你需要

form_for @user do |f|
  f.fields_for :organization_users do |ff|
    ff.fields_for :organization
于 2010-07-19T18:08:13.380 回答
0

还可以阅读关于 Accepts_nested_attributes_for 的一篇很棒的文章,当您想要一个表单来满足多个模型时,它非常有用。

http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/

希望你会喜欢这个。

谢谢

拉梅什瓦尔

于 2012-11-21T05:41:21.513 回答