0

问题:我的目标是在用户页面下列出项目,并在此用户页面上列出的每个项目下呈现评论框。但是当我尝试呈现评论框表单时,我收到了路由错误。我知道这是因为它无法提取项目的 ID。我的猜测与控制器有关,但尚未弄清楚。有人知道我该如何解决这个问题吗?

Routing Error
No route matches {:controller=>"comments", :format=>nil, :project_id=>#<Project id: nil...>}

对于我的应用程序,我为用户、项目和评论创建了模型和控制器。评论属于项目,项目属于用户

用户.rb

has_many :projects

项目.rb

has_many :comments
belongs_to :user

评论.rb

belongs_to :project

路线.rb

resources :users do
  resources :projects do
    resources :comments
  end
end

resources :projects do
  resources :comments 
end

resources: comments

查看/用户/projects.html.erb

<%= render @projects %>

查看/项目/_project.html.erb

<%= project.content %>
<%= render 'comments/form' %>

查看/评论/_form.html.erb

<%= form_for([@project, @project.comments.build]) do |f| %>
    <div class="field">
    <%= f.text_area :content, :class => "span12", :rows => "3" %>
    </div>

    <%= f.hidden_field :user_id, :value => current_user.id %>

    <div class="actions">
    <%= f.submit "Add Comment", :class => "btn btn-header" %>
    </div>
<% end %>

评论控制器.rb

def create
  @project = Project.find(params[:project_id])
  @comment = @project.comments.create!(params[:comment])

  if @comment.save
    redirect_to projects_user_path(@project.user)
  end   
end

来自上述重定向的错误

NoMethodError in CommentsController#create
undefined method `user'
4

1 回答 1

0

尝试这个:

查看/项目/_project.html.erb

<%= project.content %>
<%= render 'comments/form', project: project %>

查看/评论/_form.html.erb

<%= form_for([project, project.comments.build]) do |f| %>
...

您必须通过项目才能形成部分。

希望这可以帮助!

于 2013-05-14T22:44:36.410 回答