Reputation: 54949
I have the following models
venues(id, name, ....)
categories(id, name, ....)
categories_venues(id, venue_id, category_id)
I want to create an array of the categories one venue has been associated with. The relation is of HABTM kind.
What i have tried?
@venue = Venue.friendly.find(params[:id])
categories = @venue.categories.map { |x| x.id }
Upvotes: 0
Views: 67
Reputation: 5112
i guess `has_many through` will help you out.for example:-
#####in user.rb
##association for getting all users and thier groups /vice-versa
has_many :user_groups, :dependent => :destroy
has_many :groups, :through => :user_groups
---------------------------------------------------
####in group.rb
has_many :user_groups, :dependent => :destroy
has_many :users, :through => :user_groups
-----------------------------------------------------------
#####in user_group.rb
belongs_to :group
belongs_to :user
-------------------------------------------------------------
###and we have the necessary migration(its easy... :))..
so now
@user=User.find(1)
[email protected]("name=?","Alumni")
[email protected](&:name)
if you use scopes/class methods
than...you can get more data with joins/include
Upvotes: 1
Reputation: 1416
Try this: @venue.categories.pluck(:id)
.
This will create SELECT
query for only id
field
Upvotes: 1