I am new to Rails. I am building my first application - a simple blog. I have User and Post models where each user can write many posts. Now I want to add a comment model, where each message can have many comments, and also each user can comment on any message created by any other user. In the comment model, I have
id \ body \ user_id \ post_id
the columns.
Model Associations:
user.rb
has_many :posts, dependent: :destroy has_many :comments
post.rb
has_many :comments, dependent: :destroy belongs_to :user
comment.rb
belongs_to :user belongs_to :post
So, how to define the create action in CommentsController correctly? Thanks.
UPDATE:
routes.rb
resources :posts do resources :comments end
comments_controller.rb
def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(comment_params) if @comment.save redirect_to @post else flash.now[:danger] = "error" end end
Result
--- !ruby/hash:ActionController::Parameters utf8: β authenticity_token: rDjSn1FW3lSBlx9o/pf4yoxlg3s74SziayHdi3WAwMs= comment: !ruby/hash:ActionController::Parameters body: test action: create controller: comments post_id: '57'
As we can see, it does not send user_id and only works if I delete validates :user_id, presence: true line from comment.rb
Any suggestions?
source share