Harsha M V
Harsha M V

Reputation: 54949

Rails Mapping relational DB Ids into an Array

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

Answers (3)

Milind
Milind

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

Igor Guzak
Igor Guzak

Reputation: 2165

you could use:

@venue.category_ids

Upvotes: 2

Ivan Shamatov
Ivan Shamatov

Reputation: 1416

Try this: @venue.categories.pluck(:id).

This will create SELECT query for only id field

Upvotes: 1

Related Questions