database - How to make the association in model so I can get all places of user_places's id in rails console? -


i have 2 tables example:

user_places

 ---------------- | id | place_id| ---------------- | 1  | 1       | ---------------- | 1  | 5       | ---------------- | 1  | 6       | ---------------- | 2  | 8       | 

and places table

 -------------------------------------------- | id | title   |  description  | image_url | -------------------------------------------- | 1  | 1       | description1  | image1    | -------------------------------------------- | 2  | 5       | description2  | image2    | -------------------------------------------- | 3  | 6       | description3  | image3    | -------------------------------------------- | ...| ...     | description4  | image4    | 

how make association in both models can places of user_places's id = 1 in rails console?

you'll want foreign_keys, pertaining rails.

rails way interact relational database. such, if know how correctly structure relational db, you'll able better understand rails' activerecord associations, , how fit applications.

enter image description here

--

how make association in both models can places of user_places's id = 1

you'd this:

#app/models/user.rb class user < activerecord::base    has_and_belongs_to_many :places end  #app/models/places.rb class place < activerecord::base    has_and_belongs_to_many :users end 

this means have change user_places table following:

#places_users #user_id | place_id 

this allow call:

$ @user = user.find "1" $ @user.places #-> 1,5,6 

--

the other answer recommended has_many :through relationship. whilst allows add other data join model, means have include user_places model no real reason (at stage).

i recommend using has_and_belongs_to_many moment. limits only having references in join table, makes entire association simpler:

enter image description here

the big caveat here you'll need change user_places table have alphabetical nameflow (places_users), , make sure have 2 foreign_keys columns: user_id | place_id


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -