Rails 3, comments in a nested form, wrong routes?

北城以北 提交于 2019-12-11 04:47:12

问题


I have a Posts model, which has many posts in many languages. It's a bit non-standard, but to illustrate:

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

I.e. a Post has one EngPost. Whereas EngPost is defined in the model as:

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

And finally, the eng_comments model is:

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

The routes.rb defines:

resources :posts do
  resource :eng_posts
end

resource :eng_post do
  resources :eng_comments
end

resources :eng_comments

The problem - can't render the Post with the eng_comments, I tried:

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

and tried:

<% form_for @comment do |f| %>

This results in error

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

Thanks.


回答1:


The eng_comments also need to be nested:

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

If you were using
<% form_for ([@post.eng_post, @post.eng_post.eng_comments.build]) do |f| %> then your current routes would work.


ps:
you might want to prepare all the variables in the controller (especially the eng_comment):

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

So that you can do:

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

The advantage is that you'll be able to use the exact same form to edit the comment (even if the comments can't be edited in your app, I think it's a good practice).




回答2:


I think you may want to nest the resources like this in your routes.rb

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

This should give you paths like this: /posts/:id/eng_posts/:id/eng_comments/[:id]

That way the post_eng_post_eng_comments_path should exist.. (better try it out with rake routes)



来源:https://stackoverflow.com/questions/8687990/rails-3-comments-in-a-nested-form-wrong-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!