简体   繁体   English

Rails-路由错误-从另一个模型调用模型

[英]Rails - Routing Error - Calling a model from another model

Question: My goal is to list projects under the user's page, and have comment box render under each project that is listed on this user page. 问题:我的目标是在用户页面下列出项目,并在此用户页面上列出的每个项目下显示注释框。 But when I do try to render the comment box form, I get a routing error. 但是当我尝试呈现注释框表单时,出现了路由错误。 I know this is because it is not being able to pull out the ID of the project. 我知道这是因为它无法提取项目的ID。 My guess is something to do with the controller but have not figured out. 我的猜测与控制器有关,但尚未弄清楚。 Does somebody know how I can solve this? 有人知道我该怎么解决吗?

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

For my application, I have created models and controllers for Users, Projects, and Comments. 对于我的应用程序,我为用户,项目和注释创建了模型和控制器。 Comments belong to Projects and Projects belong to Users 注释属于项目,项目属于用户

user.rb user.rb

has_many :projects

project.rb project.rb

has_many :comments
belongs_to :user

comment.rb comment.rb

belongs_to :project

routes.rb routes.rb

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

resources :projects do
  resources :comments 
end

resources: comments

view/users/projects.html.erb view / users / projects.html.erb

<%= render @projects %>

view/projects/_project.html.erb view / projects / _project.html.erb

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

view/comments/_form.html.erb view / comments / _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 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

Error from the redirect above 上面的重定向错误

NoMethodError in CommentsController#create
undefined method `user'

Try this: 尝试这个:

view/projects/_project.html.erb view / projects / _project.html.erb

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

view/comments/_form.html.erb view / comments / _form.html.erb

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

You have to pass the project to form partial. 您必须通过项目才能形成局部项目。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM