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 #should have user_id: integer in Comment
belongs_to :post #should have post_id: integer in comment
delegate :username, to: :user, allow_nil: true
end
В контроллере сообщений: -
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(comment_params)
@comment.user = current_user
if @comment.save
flash[:success] = "Comment saved successfully!"
redirect_to post_path(@post)
else
flash[:error] = @comment.errors.full_messages.to_sentence
redirect_to post_path(@post)
end
end
После этого вы можете получить все пользовательские данные любого комментария: -
comment = Comment.find(#id_of_comment)
comment.username => #will return username because of delegation
Ссылка для делегирования