5

我意识到这可能是一个非常基本的问题,但我现在已经花了好几天的时间回到这个问题上,出于某种原因,谷歌只是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我还查看了 O'Reilly 的 Ruby Cookbook 和 Rails API,但我仍然坚持这个问题. 我找到了一些关于多态关系的信息,但这似乎不是我所需要的(尽管如果我错了请告诉我)。

我正在尝试调整Michael Hartl 的教程以创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。

我的主要问题是:我不知道如何将当前文章的 id 放入评论控制器。

User 类的关系:

class User < ActiveRecord::Base

has_many :articles
has_many :comments, :dependent => :destroy

Article 类的关系:

class Article < ActiveRecord::Base

belongs_to :user
has_many :comments, :dependent => :destroy

Comment 类的关系:

class Comment < ActiveRecord::Base

belongs_to :user
belongs_to :article

这是我的 CommentsController(关于页面呈现在 else 中只是为了让我暂时明白):

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' %>
4

2 回答 2

9

I agree with you, polymorphic is not what you want here. I think your current associations look pretty good.

I assume that in your routes.rb you have a setup something like this. Correct me if I'm wrong:

resources :articles do
  resources :comments
end

But if this is the case, you should change the create action in your CommentsController to use params[:article_id] instead of params[:id]

@article = Article.find(params[:article_id])

That should fix the problem where it can't find an Article without an ID

于 2011-03-29T04:36:06.450 回答
0

阅读有关多态关联的信息,我认为它们对您的情况非常有帮助。

于 2011-03-29T03:57:15.863 回答