Reputation: 177
I'm following this tutorial :
http://guides.rubyonrails.org/getting_started.html#adding-a-second-model
It works when using commenter
and comment
where the user can add a name and message but I want to associate the comment with a user id (I already have users)
It uses
rails generate model Comment commenter:string body:text post:references
but I want to replace commenter:string
with a user id association (user_id:integer
?). In a previous question someone suggested author_id:integer
but it did not work. Not sure where to start and there doesn't seem to be any tutorials on the subject (I have read RoR help guides on associations etc but can't find the correct way to generate a user id with the comment model)
comments_controller.rb
def create
@listing = Listing.find(params[:listing_id])
@comment = @listing.comments.create(params[:comment])
redirect_to listing_path(@listing)
end
Upvotes: 0
Views: 692
Reputation: 18672
You can generate the Comment mode like this:
rails generate model Comment user:references body:text post:references
The references
type you specify will actually create a user_id:integer
column and adds a belongs_to
association to the Comment
model:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
If you do want to have a Comment#commenter
association to refer to the user rather than Comment#user
, you can define it in your Comment
model as follows:
class Comment < ActiveRecord::Base
belongs_to :commenter, class_name: 'User', foreign_key: 'user_id'
belongs_to :post
end
Upvotes: 1