我意识到这可能是一个非常基本的问题,但我现在花了几天时间回到它,出于某种原因谷歌并没有帮助我。 (我认为部分问题在于我是初学者,我不知道该问什么......)我也看过O'Reilly的Ruby Cookbook和Rails API,但我仍然坚持这个问题。我找到了一些关于多态关系的信息,但似乎并不是我所需要的(尽管如果我错了就让我知道)。
我正在尝试调整Michael Hartl's tutorial来创建包含用户,文章和评论(不使用脚手架)的博客应用程序。我希望评论既属于用户又属于文章。
我的主要问题是:我无法弄清楚如何将当前文章的ID添加到评论控制器中。
User类的关系:
class User < ActiveRecord::Base
has_many :articles
has_many :comments, :dependent => :destroy
文章类的关系:
class Article < ActiveRecord::Base
belongs_to :user
has_many :comments, :dependent => :destroy
评论类的关系:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :article
这是我的CommentsController(关于在其他地方呈现的页面只是为了让我暂时明白):
class CommentsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
def new
@comment = Comment.new
end
def create
@article = Article.find(params[:id])
@comment = current_user.comments.build(params[:comment])
@comment.article_id = @article.id
if @comment.save
flash[:success] = "Comment created!"
redirect_to '/contact'
else
render '/about'
end
end
def destroy
end
end
当我以用户身份登录并尝试在文章上创建评论时,我会收到“找不到没有ID的文章”。我无法弄清楚如何将当前文章的id添加到评论控制器中。
如果您需要我发布更多代码,请与我们联系。
编辑:这是我的_comment_form.html.erb部分,我在show.html.erb视图的底部调用该文章:
<%= form_for ([@article, @article.comments.build]) do |f| %>
<div class="field">
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
此处还有文章的show.html.erb:
<heading>
<h1><%= @article.heading %></h1>
<p>Posted <%= time_ago_in_words(@article.created_at) %> ago by <%= @article.user.name %></p>
</heading>
<p><%= @article.content %></p>
<footer><p>
<% unless @article.comments.empty? %>
<%= @article.comments.count %>
<% end %> comments</p></footer>
<% unless @article.comments.empty? %>
<%= render @comments %>
<%= will_paginate @comments %>
<% end %>
<%= render 'shared/comment_form' %>
答案 0 :(得分:9)
我同意你的看法,多态并不是你想要的。我认为你目前的协会看起来很不错。
我假设你的routes.rb中有一个这样的设置。如果我错了,请纠正我:
resources :articles do
resources :comments
end
但是如果是这种情况,你应该更改CommentsController中的create动作以使用params [:article_id]而不是params [:id]
@article = Article.find(params[:article_id])
这应解决无法找到没有ID的文章的问题
答案 1 :(得分:0)
了解polymorphic associations,我认为它们对您的情况非常有帮助。