【问题标题】:Associations in Ruby on Rails 4Ruby on Rails 4 中的关联
【发布时间】:2016-08-22 12:43:24
【问题描述】:

我有一个关于 Rails 关联的问题。 我正在尝试为具有主题的帖子创建评论。 所以我的 routs 文件看起来像这样:

resources :subjects do
  resources :post do
    resources :comments
  end
end

现在我正在尝试在帖子的 show.html.erb 文件中创建一个表单,以便有人可以创建评论。 我已经尝试过这种方法,我在 rails 指南中找到了:

'posts/show.html.erb'

<%= form_for {[@post, @post.comments.build]} do |f| %>
//fill in form
<% end %>

'posts.controller.rb'

def show
  @post = Post.find(params[:id])
end

但这给了我一个错误。如果您需要任何其他代码部分,请随时询问。

错误信息

ActionView::Template::Error (undefined method `post_comments_path' for #<#<Class:0x007f9a4429d5e8>:0x007f9a42c01fc8>):
 8:   <strong>Text:</strong>
 9:   <%= @post.text %>
10: </p>
11: <%= form_for ([@post, @post.comments.build]) do |f| %>
12:     <p>
13:       <%= f.label :text %><br>
14:       <%= f.text_area :text %>

【问题讨论】:

  • 你能分享你的控制台日志吗?
  • 添加到我的问题中
  • 您在哪一行收到此错误?
  • 第 11 行,我将更新错误消息 -> html 标签已应用于消息
  • 尝试在您的控制器中构建您的 post.build_comment 在不同的变量中显示操作,并将 url 选项添加到您的 form_for 并给出您的表单将继续提交的方法的路径。

标签: ruby-on-rails ruby-on-rails-4 associations


【解决方案1】:

这些路径在resources :subjects 下分组,因此您的路径将是subjects_post_comments_path,或者如果您更喜欢使用多态路径,它将是[@subjects, @post, @post.comments.build]

您可以运行 rake routes | grep comments 来查看所有 cmets 路线的路径。

【讨论】:

  • resources :post 也应该是resources :postsresource :post
  • 可能有用的建议:您可以随时使用rake routes 来查看可用路线的列表。它们还显示可用的路径。在该列表中,文本的第一位(如果存在)将向您显示路径。通常,如果您将 _path 添加到末尾,您会找到上面 Jarred 回答中描述的相关路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多