【发布时间】:2015-03-17 05:40:55
【问题描述】:
我正在学习 Rails(已安装 4.2)并正在开发一个社交网络模拟应用程序。 我已经在用户和帖子之间建立了一对多的关系,现在我正在尝试向帖子添加评论。经过多次尝试并遵循documentation on rubyonrails.org,我最终得到了以下设置:
用户模型
has_many :posts, dependent: :destroy
has_many :comments, through: :posts
后模型
belongs_to :user
has_many :comments
评论模型
belongs_to :user
评论是从 Post show 页面发起的,所以 后控制器拥有:
def show
@comment = Comment.new
end
现在的问题是:在 Comments Controller 中,创建新记录的正确方法是什么。 我尝试了以下和其他许多方法,但没有成功。
def create
@comment = current_user.posts.comment.new(comment_params)
@comment.save
redirect_to users_path
end
(current_user 来自 Devise)
另外,之后,如何选择评论对应的帖子?
谢谢
【问题讨论】:
-
current_user.posts是帖子的集合。has_many关联位于单个帖子上,而不是它们的集合。 (编辑:我应该作为答案提交。)
标签: ruby-on-rails ruby-on-rails-4 has-many-through