Hello Soldiers!
I had mentioned in the previous article that I would explain custom routing in rails using my own project. Since I am a noob I have hit a wall and so will skip it for now and share with you something amazing I stumbled onto while building the project.
We know in Ruby, everything is an Object.
And how easy it is to retrieve comments that belongs to a particular post.
@post.comments
We know underlying is a join table of relational-database between Posts and Comments. To identify comments with its Post each comment consists of a foreign_key attribute :post_id.
To create this join table Comments model we used the migration,
rails g model Comment body:string references:post
Which in-turn creates a migration similar to:
def change
create_table :comments do |t|
t.string :body
t.references :post
end
add_foreign_key :comments, :posts
end
This creates a Comments table with a foreign_key :post_id which refers to the primary_key :id of Post table.
Now, to add reference to already pre-existing tables there are many ways as explained here,
Just out of curiosity I simply generated a migration to add :post_id column to Comments table and check if it would work.
rails g migration add_post_id_to_comments post_id:integer
Which in turn creates a migration similar to:
def change
add_column :comments, :post_id, :integer
end
And guess what?!
IT WORKS.
The beauty of Ruby on Rails!
Rails follow Convention over Configuration style hence Rails automatically declares a relation between Comment and Post models using the power of Ruby! <3
Thats it for today. Lonely weekend plans.
Goodnight!
Love,
M.
liked_the_post == true ? comment and share : comment and share