从另一个控制器访问和添加记录

时间:2013-01-13 23:09:24

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我有一个模特

class Rcomment < ActiveRecord::Base
  attr_accessible :comment, :rating

  belongs_to :recipe
  belongs_to :user
end

我正在尝试通过配方的显示视图添加评论。我用虚拟数据填充了rcomment表,它通过以下方式显示:

@recipe = Recipe.find(params[:id])
@comments = @recipe.rcomments

所以我试过了     @newcomments = @ recipe.rcomments.build(params [:recipe])

但它根本不起作用,有错误:     #&lt;#:0x25ccd10&gt;

的未定义方法`rcomments_path'

如何让它显示可用的form_for?

%= form_for(@newcomments) do |f| %>

      <%= f.label :Comments %>
      <%= f.text_field :comment%>

      <%= f.label :ratings %>
      <%= f.text_field :rating %>

      <%= f.submit "Submit Comment", class: "btn btn-large btn-primary" %>
    <% end %>

1 个答案:

答案 0 :(得分:0)

您已为Rcomment创建创建了一个表单,但您的routes.rb中没有rcomments条目。但是,我认为最适合您的问题是通过配方创建rcomments。您可以使用accepts_nested_attributes_forfields_for

执行此操作

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

所以,像这样 -

在食谱模型中,添加:

attr_accessible :rcomments_attributes
accepts_nested_attributes_for :rcomments

在你的食谱中#show view:

<%= form_for(@recipe) do |f| %>
  <% f.fields_for :rcomments do |cf| %>
    <%= cf.label "Comments" %>
    <%= cf.text_field :comment%>

    <%= cf.label "Ratings" %>
    <%= cf.text_field :rating %>
  <% end %>

  <%= f.submit "Submit Comment", class: "btn btn-large btn-primary" %>
<% end %>
相关问题