Rails从嵌套属性中获取数据

时间:2015-03-04 12:37:02

标签: ruby-on-rails join nested-attributes

我有三种模式:

data_set.rb

class DataSet < ActiveRecord::Base
  has_many :browse_options
  accepts_nested_attributes_for :browse_options, allow_destroy: true 
end

browse_option.rb

class BrowseOption < ActiveRecord::Base
  belongs_to :data_set
  has_many :browse_option_datas
  accepts_nested_attributes_for :browse_option_datas, allow_destroy: true 
end

browse_option_data.rb

class BrowseOptionData < ActiveRecord::Base
  belongs_to :browse_options

  has_one :tradesman
end

我希望能够在数据集视图中显示与数据集关联的所有商人,而不会重复。有没有办法可以使用连接方法在控制器中执行此操作?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过在模型之间设置has_many through关系来实现此目的。有great docs on this topic

class DataSet
  has_many :browse_options
  has_many :browse_option_datas, :through => :browse_options
  has_many :tradesmen, :through => :browse_option_datas
end

class BrowseOption
  belongs_to :data_set
  has_many :browse_option_datas
end

class BrowseOptionData
  belongs_to :browse_options
  belongs_to :tradesman
end

class Tradesman
  has_many :browse_options_data
end

修改:在一些discussion in chat之后,我们还意识到了Tradesman&amp;之间的关系。 BrowseOptionData需要一些修复。

现在,在您的控制器中,您可以致电:

@data_set = DataSet.first
@tradesmen = @data_set.tradesmen # .uniq if you don't want any duplicates