Rails:如何在has_many上保存额外的字段

时间:2014-03-27 00:58:45

标签: ruby-on-rails save has-many

我实际上有一个has_many通过关联,以便从用户表中链接父母和孩子。 所以这就是我在模特中所得到的:

class User < ActiveRecord::Base
  has_many :parents_to_children, class_name: ParentsUser, foreign_key: :children_id
  has_many :parents, through: :parents_to_children, source: :parent

  has_many :children_to_parents, class_name: ParentsUser, foreign_key: :parent_id
  has_many :childrens, through: :children_to_parents, source: :children
end

class ParentsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :parent, class_name: User
  belongs_to :children, class_name: User
end

我的联接表如下所示:

|----------------------------------------------------|
| id |  children_id  |  parent_id  |  relation_type  |
|----------------------------------------------------|

为了保存数据,我正在做(到目前为止):

resource.childrens << user if user

这很好用,但不幸的是,relation_type没有保存(params [:user] [:relation])。

所以我试图这样做:

resource.childrens.build(childrens: [user], relation_type: params[:user][:relation]) if user

但我收到了错误:unknown attribute: relation_type

关于如何以优雅的方式实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:0)

您缺少accepts_nested_attributes_for。将其写在User模型

accepts_nested_attributes_for :parents_user

这可以解决问题。