【问题标题】:nested resources and build method for making association嵌套资源和建立关联的方法
【发布时间】:2013-06-05 10:11:16
【问题描述】:

我在三个模型之间关联:用户、帖子、评论。评论是 Post 的嵌套资源。

routes.rb

resources :posts do
 resources :comments
end

用户模型:

has_many :comments

后模型:

has_many :comments

评论模型:

belonsg_to :user
belonsg_to :post

目标是当用户发表新评论时,它会创建与该用户的关联。所以你可以看到它就像用户知道他所做的所有 cmets。

cmets_controller.rb

def create
  @post = Post.find(params[post_id]
  @comment = @post.comments.build[:comment]
  current_user.comments >> @comment
  ....
end

new.html.erb

<% form_for [@post, @post.comment.build]  do |f| %>
.....
<% end %>

这给了我一个错误,没有方法 cmets。我应该怎么做才能避免这种情况?

【问题讨论】:

  • 什么是 Prog 模型?它是belongs_to 而不是belons_to
  • 你打错字了,这可能是你的问题吗?你写了&lt;% form_for [@post, @post.comment.build] do |f| %&gt; 而不是&lt;% form_for [@post, @post.comments.build] do |f| %&gt;。所以comments 而不是comment

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


【解决方案1】:

您很可能在 new.html.erb 中缺少“S”字母。应该是cmets:

<% form_for [@post, @post.comments.build]  do |f| %>
  .....
<% end %>

如果您没有发布更多逻辑,请告诉我们。您的创建操作看起来不错。尝试查看控制台 student_id 属性,如果它填充的 ID 比你好。干杯。

【讨论】:

    【解决方案2】:

    使用

    @post.comments.build
    

    代替

    @post.comment.build (x)
    

    这应该可以工作,如果可能的话,将这行代码从视图移动到控制器

    了解更多信息 http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

    【讨论】:

      【解决方案3】:

      new.html.erb 文件中,您使用“s”表示构建方法。

      应该是,

      <% form_for [@post, @post.comments.build]  do |f| %>
      .....
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多