[英]belongs_to association — how do I call it?
Silly question, but I can't find an example . 愚蠢的问题,但我找不到一个例子。 . 。 . 。
My User model has_many Comments. 我的用户模型has_many评论。 My Comments model belongs_to User. 我的评论模型属于用户。 The Comments table has a column user_id, which I've included in my db:seeds file. 注释表中有一列user_id,我将其包含在db:seeds文件中。 Every comment has a user_id. 每个评论都有一个user_id。
So how do I refer to a comment's user? 那么,我如何指代评论的用户呢? "Comment.user" seems like it should work, but I keep getting error messages saying user is nil, or an undefined method. “ Comment.user”似乎应该可以工作,但是我不断收到错误消息,指出user为nil或未定义的方法。
In particular, I want to refer to attributes of user through comment, such as comment.user.avatar. 特别是,我想通过注释来引用用户的属性,例如comment.user.avatar。
Are you referring to the class Comment when you try and access the user, or the actual instance object? 您在尝试访问用户或实际实例对象时是在引用注释类吗? Doing something like the following should work: 进行以下操作应该可以:
@user = User.new(username: "Bob")
@comment = Comment.new(comment: "Hello World!", user: @user)
puts @comment.user.username
However, if you are doing Comment.user this will fail because you are not referencing a specific instance but rather the model itself. 但是,如果您正在执行Comment.user,则此操作将失败,因为您不是在引用特定实例,而是在引用模型本身。 If so, that would explain what is causing your errors. 如果是这样,那就可以解释造成您错误的原因。
Stranger and stranger . 陌生人和陌生人。 . 。 . 。 today, I'm not getting the confusing error messages. 今天,我没有收到令人困惑的错误消息。 So my code does work! 所以我的代码确实有效! Just in case people look up this question in the future, I'll do what I should've done in my question, and show more of my code. 以防万一将来人们查询这个问题,我将做我应该做的事情,并显示更多代码。 Again, Comments belongs_to User. 再次,评论属用户。
- @comments.each do |com|
= markdown com.body
%small
submitted
= time_ago_in_words(com.created_at)
ago by
= image_tag(com.user.avatar.tiny.url) if com.user.avatar?
= link_to((com.user.name || com.user.email), com.user)
%br
Thanks for your input, @raznic! 感谢您的输入,@ raznic!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.