【问题标题】:rails nested attributes has_many throughrails 嵌套属性 has_many 到
【发布时间】:2012-07-19 16:26:44
【问题描述】:

我有三个模型。父、子、类型和关系。关系是引用父、子和类型的富连接模型。

问题在于,当创建了一个孩子并创建了关系表时,关系表中的 parent_id 没有被填充。只有子项和类型会自动填充。

父.rb

attr_acccessible :relationships_attributes

has_many :relationships
has_many :children, :through => :relationships
has_many :types, :through => :relationships

child.rb

attr_acccessible :relationships_attributes

has_many :relationships
has_many :parents, :through => :relationships
has_many :types, :through => :relationships

accepts_nested_attributes_for :relationships

relationship.rb

attr_accessible :parent_id, :child_id, :type_id
belongs_to :parent
belongs_to :child
belongs_to :type

children.controller

def new
 @child = Child.new
 @child.relationships.build
end

def create
 @child = Child.new(params[:child])
 if @child.save
  redirect_to current_user
 else
  render "new"
 end
end

new.html.erb

<%= simple_form_for @child do |f| %>
  <%= f.input :first_name, :label => 'First Name' %>
  <%= f.input :gender, :as => :select, :collection => ['Male', 'Female'] %>
  <%= f.association :relation_types, :as => :collection_select %>


  <%= f.button :submit, :class => "primary" %>

<% end %>

请帮忙。

谢谢!

【问题讨论】:

    标签: ruby-on-rails-3 nested-attributes simple-form


    【解决方案1】:

    看来你忘记了很多事情:

    @child.relationships.build 
    

    应该是

    @child.relationships.build :parent_id => ...
    

    并且在视图中 而是

    f.association :relation_types, :as => :collection_select
    

    使用

    f.field_for :relationships do |g|
      g.association :types, :as => :collection_select
      g.hidden :parent_id #need to save this
    

    【讨论】:

    • 谢谢。还有其他方法可以合并父 ID 吗?我宁愿不使用隐藏字段。
    • 如果你不希望它在父 id 中也许你可以将它隐藏在参数中(更改表单 url 或更改 routes.rb 使这个资源嵌套(这并不容易))
    • 你也可以使用@child = @parent.children.build
    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 2016-03-23
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多