I\'m new to Rails. I\'m building my first app - simple blog. I have User and Post models, where each user can write many posts. Now I want to add Comment model, where each post
Associations
To give you a definition of what's happening here, you have to remember whenever you create a record, you are basically populating a database. Your associations are defined with foreign_keys
When you ask how to "add comments to User
and Post
model" - the bottom line is you don't; you add a comment to the Comment
model, and can associate it with a User
and Post
:
#app/models/comment.rb
Class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
This prompts Rails to look for user_id
and post_id
in the Comment
model by default.
This means if you wanted to create a comment directly, you can associate it to either of these associations by simply populating the foreign_keys
as you wish (or use Rails objects to populate them)
So when you want to save a comment
, you can do this:
#app/controllers/comments_controller.rb
Class CommentsController < ApplicationController
def create
@comment = Comment.new(comment_params)
end
private
def comment_params
params.require(:comment).permit(:user_id, :post_id, :etc)
end
end
Conversely, you can handle it by using standard Rails objects (as the accepted answer has specified)