【问题标题】:Rails 3, comments in a nested form, wrong routes?Rails 3,嵌套形式的评论,错误的路线?
【发布时间】:2012-01-31 01:25:57
【问题描述】:

我有一个 帖子 模型,其中包含许多 语言 的帖子。这有点不标准,但为了说明:

class Post < ActiveRecord::Base
  has_one :eng_post, :dependent => :destroy         # <-- HAS_ONE!
  accepts_nested_attributes_for :eng_post, :allow_destroy => true
end

即一个 Post 有一个 EngPost。而 EngPost 在模型中被定义为:

class EngPost < ActiveRecord::Base
  belongs_to :post
  has_many :eng_comments, :dependent => :destroy
  accepts_nested_attributes_for :eng_comments, :allow_destroy => true
  attr_accessible :eng_comments_attributes
end

最后,eng_cmets 模型是:

class EngComment < ActiveRecord::Base
  belongs_to :eng_post, :foreign_key => "eng_post_id"
end

routes.rb 定义:

resources :posts do
  resource :eng_posts
end

resource :eng_post do
  resources :eng_comments
end

resources :eng_comments

问题 - with eng_cmets 无法渲染帖子,我试过了:

<% form_for ([@post, @post.eng_post, @post.eng_post.eng_comments.build]) do |f| %>

并尝试过:

<% form_for @comment do |f| %>

这会导致错误

undefined method `post_eng_post_eng_comments_path' for #<#<Class:0x000000067de2a8>:0x000000067c4498>

谢谢。

【问题讨论】:

    标签: ruby-on-rails forms routes nested has-one


    【解决方案1】:

    eng_cmets 也需要嵌套:

    resources :posts do
       resource :eng_post do #no 's'
           resources :eng_comments
       end
    end
    
    resources :eng_posts do
         resources :eng_comments
    end
    
    resources :eng_comments
    

    如果您使用的是
    &lt;% form_for ([@post.eng_post, @post.eng_post.eng_comments.build]) do |f| %&gt; 那么你当前的路线就可以了。


    ps:
    您可能需要准备控制器中的所有变量(尤其是 eng_comment):

    def new
        @post = Post.find...
        @eng_comment = @post.eng_post.eng_comments.build
    end
    

    这样你就可以做到:

    <% form_for ([@post, @post.eng_post, @eng_comment]) do |f| %>
    

    优点是您将能够使用完全相同的表单来编辑评论(即使无法在您的应用中编辑 cmets,我认为这是一个很好的做法)。

    【讨论】:

    • 罗宾,感谢您的回答。但它渲染的唯一方法是使用 。仍然没有呈现 cmets 表单,调试的输出是 --- !ruby/object:EngComment attributes: id: !!null eng_post_id: 97 full_name: !!null website: !!null email: !!null comment: ! !null created_at: !!null updated_at: !!null
    • 对不起,您的建议有效,添加资源后:eng_posts do resources :eng_cmets end
    【解决方案2】:

    我想你可能想在你的routes.rb中嵌套这样的资源

    resources :posts do
      resource :eng_posts do 
        resource :eng_comments
      end
    end
    

    这应该给你这样的路径:/posts/:id/eng_posts/:id/eng_comments/[:id]

    这样post_eng_post_eng_comments_path应该存在..(最好用rake routes试试)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      相关资源
      最近更新 更多