sql - Merge a column with results from an ActiveRecord query in Rails -


i have 3 following tables in ruby on rails 4:

the "decision" table:

class decision < activerecord::base     validates :title,  presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }     validates :colour,  presence: true, length: { maximum: 20 }, uniqueness: { case_sensitive: false }     has_many :decision_datafields, dependent: :destroy     has_many :datafields, through: :decision_datafields       def datafields         datafield.where(id: self.decision_datafields.select("datafield_id"))     end  end 

the "decisiondatafield" table (linking table):

class decisiondatafield < activerecord::base     validates :min_score, presence: true     validates_inclusion_of :min_score, :in => 1..10     belongs_to :decision     belongs_to :datafield end     

the "datafield" table:

class datafield < activerecord::base     validates :title,  presence: true, length: { maximum: 100 }, uniqueness: { case_sensitive: false }     has_many :decision_datafields, dependent: :destroy     has_many :decisions, through: :decision_datafields       has_many :score_options, dependent: :destroy      def decisions         decision.where(id: self.decision_datafields.select("decision_id"))     end end 

there score options table, isn't necessary problem.

anyway, i'd able do query this:

decision.first.datafields 

... , have activerecord retrieve list of first decision's datafields, along corresponding min_score value decisiondatafields linking table.

right now, above query return this:

#<activerecord::relation [#<datafield id: 1, title: "df1", created_at: "2015-03-28 09:59:26", updated_at: "2015-03-28 09:59:26">, #<datafield id: 2, title: "df2", created_at: "2015-03-28 09:59:26", updated_at: "2015-03-28 09:59:26">]> 

... nice, want this:

#<activerecord::relation [#<datafield id: 1, title: "df1", created_at: "2015-03-28 09:59:26", updated_at: "2015-03-28 09:59:26", min_score: 5>, #<datafield id: 2, title: "df2", created_at: "2015-03-28 09:59:26", updated_at: "2015-03-28 09:59:26, min_score: 7">]> 

the difference min_score decisiondatafield linking table has been joined records returned query.

thanks!

this might work (haven't tested it):

class decision < activerecord::base   ...   def data_fields     datafield.includes(:decision_datafield).select("datafields.*, decision_datafields.min_score").where(id: self.decision_datafields.select("datafield_id"))   end end 

call decision.first.data_fields


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -