简体   繁体   中英

How to get information from child table

I have a Users model with has_many :comments Each comment records the current_user to the commenter column.

How can I call @commenter.username in my view and show the commenter's username?

Currently in comments_controller using: @commenter = User.find("2") will pull the correct information. I would like to use something along the lines of: @commenter = User.find_by_id(:commenter)

From the comments, it sounds like you have this Comment model:

class Comment < ActiveRecord::Base
  belongs_to :user
end

The comment model represents comments on a user's page , where the user model is defined as:

class User < ActiveRecord::Base
  has_many :comments
end

There is also a commenter column on the comments table to store the user who posted the comment (on the other user's page).

First, I would recommend using commenter_id for this column rather than commenter , since this is the convention for storing ids of any kind.

Assuming that you have a commenter_id column on the comments table, you would then define a second relationship as follows:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commenter, class_name: "User", foreign_key: :commenter_id
end

The commenter relationship defines the user who wrote the comment, rather than the user whose page the comment is on .

For the other side of this relationship, update your User model:

class User < ActiveRecord::Base
  has_many :comments
  has_many :page_comments, class_name: "Comment", foreign_key: :commenter_id
end

Here, page_comments defines the comments this user has posted on other users' pages.

Then if you have a @comment , you can get the commenter's name with simply:

@comment.commenter.name

As long as you setup your column names and models correctly, dealing with getting information like this should be very simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM