Reputation: 533
I have a User Model:
id, name, email
has_many :microposts, dependent: :destroy
has_many :comments, dependent: :destroy
A Micropost Model:
id, content, title
belongs_to :user
has_many :comments, dependent: :destroy
and a Comment Model:
id, content, user_id, micropost_id
belongs_to :user
belongs_to :micropost
has_one :micropost
has_one :user
I would like to access the User Name of each comment through a comment itself. For example, I can get the user's name through micropost with micropost.user.name
which will give me the User name of the user associated with a particular micropost. In the same vain, I'd like something like comment.user.name or in sql terms
select user.name from User as user join Comment as comment where user.id = comment.user_id and comment.id = 12;
When I try to run comment.user.name
I get an error:
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."comment_id" = ? LIMIT 1 [[nil, 3]]
SQLite3::SQLException: no such column: users.comment_id: SELECT "users".* FROM "users" WHERE "users"."comment_id" = ? LIMIT 1
I see the problem with the SQL is there is no users.comment_id, but I would like for the SQL to actually be users.id. How can I write this?
Upvotes: 0
Views: 47
Reputation: 1349
From your code what i understand your comment model would be.
class Comment < ActiveRecord::Base
attr_accessible :id, :content, :user_id, :micropost_id
belongs_to :user
belongs_to :micropost
end
Then in your comments controller, which you access through the micropost_comments_path(@micropost) URL helper you can do the following to build the association in the create action:
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
...
end
Upvotes: 0
Reputation: 7339
Remove the has_one
declarations from your comment model. In this relationship, a comment will only ever have one user and one micropost, as denoted by belongs_to
. Add has_one is confusing it.
Simplifying it should remove your error.
# app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :micropost
end
Upvotes: 1