3

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.

Community
  • 1
  • 1
Jayson Lane
  • 2,828
  • 1
  • 24
  • 39

1 Answers1

3

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
Community
  • 1
  • 1
Bradley Priest
  • 7,438
  • 1
  • 29
  • 33
  • worked perfect! so this code selects the list_position (list_items.list_position) and creates 'list_position' (as list_position) for each wish? – Jayson Lane Feb 20 '12 at 02:40
  • Yeah, you can call it whatever you want, but unless you have a `list_position` attribute on your wish object as well, that should do the trick – Bradley Priest Feb 20 '12 at 02:43