有很多通过关系接受嵌套属性

时间:2015-03-04 18:45:54

标签: ruby-on-rails associations nested-attributes has-many-through

我明白为了使用嵌套属性我需要使用一个有很多通过关系而不是一个has并且属于很多,所以我有以下设置:

class Deed < ActiveRecord::Base
    has_many :deeds_title_abstracts
    has_many :title_abstracts, through: :deeds_title_abstracts
end

class TitleAbstract < ActiveRecord::Base
    has_many :deeds_title_abstracts
    has_many :deeds, through: :deeds_title_abstracts
    accepts_nested_attributes_for :deeds
end

class DeedsTitleAbstracts < ActiveRecord::Base
  belongs_to :deeds
  belongs_to :title_abstracts
end

在我的标题摘要控制器中我有

def new
   @title_abstract = TitleAbstract.new(params[:title_abstract])
   @title_abstract.deeds.build
   respond_with(@title_abstract)
end

我在视图中使用cocoon但我不认为这是问题,因为我收到此错误:

  uninitialized constant TitleAbstract::DeedsTitleAbstract

当我通过控制台查看时,我得到以下内容

   @title_abstract =TitleAbstract.new(params[:title_abstract])
   => #<TitleAbstract id: nil, name: nil, due_date: nil, comments: nil,     created_at: nil, updated_at: nil>
   >> @title_abstract.deeds.build
   !! #<NameError: uninitialized constant TitleAbstract::DeedsTitleAbstract>

我认为我的Has Many Through模型存在问题

1 个答案:

答案 0 :(得分:0)

您的连接模型名称不是每个Rails命名约定。它应该被称为DeedTitleAbstract DeedsTitleAbstracts。因此,修复此类名称(包括数据库表名称)可能是最好的做法,而不是合并一个变通方法(如下所示)。

解决方法是将class_name选项提供给has_many :deeds_title_abstracts

has_many :deeds_title_abstracts, class_name: 'DeedsTitleAbstract'

请参阅:Naming Conventions

此外,您的belongs_to关系定义需要进行审核。 belongs_to关系应该在包含外键的模型上定义,它们应该是单数而不是复数。

以下是您的关系定义的更新(当然,在您更新了连接表迁移后,包括模型名称更改)

class Deed < ActiveRecord::Base
    has_many :deed_title_abstracts
    has_many :title_abstracts, through: :deed_title_abstracts
end

class TitleAbstract < ActiveRecord::Base
    has_many :deed_title_abstracts
    has_many :deeds, through: :deed_title_abstracts
    accepts_nested_attributes_for :deeds
end

class DeedTitleAbstract < ActiveRecord::Base
  belongs_to :deed
  belongs_to :title_abstract
end
相关问题