问题:我的目标是在用户页面下列出项目,并在此用户页面上列出的每个项目下显示评论框。但是,当我尝试渲染注释框表单时,我收到路由错误。我知道这是因为它无法提取项目的ID。我的猜测与控制器有关,但还没弄明白。有人知道如何解决这个问题吗?
Routing Error
No route matches {:controller=>"comments", :format=>nil, :project_id=>#<Project id: nil...>}
对于我的应用程序,我为用户,项目和评论创建了模型和控制器。注释属于项目和项目属于用户
user.rb
has_many :projects
project.rb
has_many :comments
belongs_to :user
comment.rb
belongs_to :project
的routes.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 %>
comments_controller.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'
答案 0 :(得分:0)
试试这个:
查看/项目/ _project.html.erb 强>
<%= project.content %>
<%= render 'comments/form', project: project %>
查看/评论/ _form.html.erb 强>
<%= form_for([project, project.comments.build]) do |f| %>
...
您必须将项目传递给部分。
希望这有帮助!