Denis Policarpo
Denis Policarpo

Reputation: 153

Searching for the active record without the last

How can I get the names of sellers that have a certain goal? Follow the model below:

enter image description here

How can I get the names of sellers that have a certain goal? I have the right database model.

I'm trying like this:

GoalSalesman.where (goal_id: 1).last.salesman.name

But so I get only the last name because of last, I wanted all the names.

How can I get all of the names?

Upvotes: 1

Views: 36

Answers (1)

mindlis
mindlis

Reputation: 1677

Try setting up the associations as:

GoalSalesman.rb
  belongs_to :goal
  belongs_to :salesman

Goal.rb
  has_many :goal_salesmen
  has_many :salesmen, through: :goal_salesmen

Salesman.rb
  has_many :goal_salesmen
  has_many :goals, through: :goal_salesmen

You should then be able to get all the names by calling

Goal.find(1).salesmen.pluck(:name)

Upvotes: 3

Related Questions