Rails 从嵌套属性获取数据

Rails getting data from 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

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

您实际上可以通过在模型之间设置 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 我们也意识到 TradesmanBrowseOptionData 之间的关系需要一些修复。

现在,在您的控制器中,您可以调用:

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