A user can create a post. Posts have comments. A comment must belong to both a user and a post, however not necessarily the user who created the post. Is the following the best way to model this:
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
If so, what is the best practice for ensuring:
user.comments.newcannot be called. I want all new posts to be created using thepostthey are associated with.- The
idof the user creating the comment is properly set when callingpost.comments.new
Otherwise, what is a better way to model this relationship?
Your models are fine.
To set the author of the comment, you’d have to do that in your controller:
Just don’t use
user.comments.new. Why do you want to make it impossible to use it?