Hello all,
I’m very new to Rails and I love it so far. However, there are some
things that aren’t so clear to me.
Let’s say a blog post can have many comments, and a comment can only
belong to one post. A user can have many posts and many comments as
well. (this part makes perfect sense):
class Comment < ActiveRecord::Base
belongs_to :posting
belongs_to :user
end
class Posting < ActiveRecord::Base
has_many :comments
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
has_many :postings
end
In the comment_controller, how would I actually go about saving the
comment with the appropriate foreign keys of the posting and user. In
the comments table I have the appropriate columns (posting_id,
user_id).
Here’s what I have in the comment_controller for creating a new comment:
def new
@comment = Comment.new
end
def create
@comment = Comment.new(params[:comment])
@comment.users_ip = request.remote_ip
@comment.users = session[:user] <— Doesn’t work… stumped
@comment.posting = @posting <---- Where I’m stumped again
if @comment.save
flash[:notice] = ‘Comment was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
Am I close at all? Is using the session[:user] the best way to get the
logged in user to associate the comment and user?
Thank you in advanced,
Ted