【问题标题】:Rails - Routing Error - Calling a model from another modelRails - 路由错误 - 从另一个模型调用模型
【发布时间】:2013-05-14 22:28:20
【问题描述】:

问题:我的目标是在用户页面下列出项目,并在此用户页面上列出的每个项目下呈现评论框。但是当我尝试呈现评论框表单时,我收到了路由错误。我知道这是因为它无法提取项目的 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

查看/users/projects.html.erb

<%= render @projects %>

查看/projects/_project.html.erb

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

查看/cmets/_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 %>

cmets_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'

【问题讨论】:

  • 您的关联有错误。 belongs_to :userbelongs_to project 是单数形式。
  • 谢谢。固定的。路由错误仍然存​​在。

标签: ruby-on-rails routing controller


【解决方案1】:

试试这个:

查看/projects/_project.html.erb

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

查看/cmets/_form.html.erb

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

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

希望这会有所帮助!

【讨论】:

  • 好的,所以它现在发布到我的数据库中,但是当我尝试将 cmets 控制器中的 redirect_to 修复到 @comment.project 时,我得到了 NoMethodError。既然评论belongs_to项目,为什么我不能做这个redirect_to?
  • 我在上面编辑了问题以显示:“redirect_to projects_user_path(@project.user)”
  • 添加到我上面问题的底部。
  • 看起来错误在User.find(params[:user_id])。检查服务器日志中的参数。
  • 那是因为params[:project_id] 为nil,@project 为nil 而user 不是nil 类的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 1970-01-01
相关资源
最近更新 更多