1

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

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

即一个帖子有一个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_comments 模型是:

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

问题 - 无法使用eng_comments 呈现帖子,我试过:

<% 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>

谢谢。

4

2 回答 2

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

于 2011-12-31T12:12:20.477 回答
2

eng_comments 也需要嵌套:

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

如果您正在使用,
<% form_for ([@post.eng_post, @post.eng_post.eng_comments.build]) do |f| %> 那么您当前的路线将起作用。


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| %>

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

于 2011-12-31T12:12:56.337 回答