Question

I have three models User, Blog and Comment.

User.rb

class User < ActiveRecord::Base
  attr_accessible blah blah      
  has_many :blogs
  has_many :comments
end

Blog.rb

class Blog < ActiveRecord::Base
    attr_accessible :user_id, :title, :content
    belongs_to :user
    has_many :comments
end

Comment.rb

class Comment < ActiveRecord::Base
    attr_accessible :user_id, :blog_id, :comment
    belongs_to :blog
    belongs_to :user
end

In create action of Comments Controller

def create
    @blog = Blog.where('id=?', params[:blog_id])
    @comment = @blog.comments.new(params[:comment])
    @comment.save
end  

Here how will I pass id of current_user in the :user_id field of comments table, I can make a hidden field for that but it's not safe. PLease help! Thanks in advance.

Was it helpful?

Solution

Would this do what you want?

def create
  @blog = Blog.where('id=?', params[:blog_id])
  @comment = @blog.comments.new(params[:comment])
  @comment.user = current_user # force the user to be the logged-in user
  @comment.save
end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top