Jayson Lane
Jayson Lane

Reputation: 2828

Nested :has_many, :through attributes

I am using a has_many :through to create an association between two models using a pass-through called  list_items :

user.rb:

  has_many :list_items
  has_many :wishes, :through => :list_items

wishe.rb:

  has_many :list_items
  has_many :users, :through => :list_items

list_item.rb:

  belongs_to :user
  belongs_to :wish

This is working great, however,  list_items has additional attributes for the model  wishes that I'd like to access based on criteria from  users ( current_user to be exact). I can currently access this attribute using code like this:

wishes_controller.rb:

  @wishes = current_user.wishes

index.html.haml:

 -wish.list_items.each do |list_item|
    -if list_item.user_id == current_user.id
        =list_item.list_position

Which works fine, however, I'm betting there's a more elegant way to do this, being able to access it like  wishes.list_position (which would pull the appropriate list_position based on the current_user id). I've looked here and here (and a number of additional places) but I have not been able to translate these concepts to my project.

Upvotes: 3

Views: 747

Answers (1)

Bradley Priest
Bradley Priest

Reputation: 7458

Check out Need data from rails join table, has_many :through

Try this.
user.rb:

has_many :wishes, :through => :list_items, :select => 'wishes.*, list_items.list_position as list_position'

This gives you:

- @wishes.each do |wish|
  = wish.list_position

Upvotes: 3

Related Questions