MikeHolford
MikeHolford

Reputation: 1931

Rails getting data from nested attributes

I have three models:

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

I want to be able to display all the tradesman associated with a data set in the data set view with no duplicates. Is there a way I can use the joins method to do this in the controller? Thanks!

Upvotes: 0

Views: 129

Answers (1)

davegson
davegson

Reputation: 8331

You can actually achieve this by setting up has_many through relationships between your models. There are 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

Edit: After some discussion in chat we also realised the relationships between Tradesman & BrowseOptionData needed some fixing.

Now, in your controller, you can call:

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

Upvotes: 1

Related Questions