代码之家  ›  专栏  ›  技术社区  ›  Ash

rails map.resources和helper url

  •  0
  • Ash  · 技术社区  · 15 年前

    我有两个这样的模型:

    class Topic < ActiveRecord::Base
      has_many :articles
    end
    
    class Article < ActiveRecord::Base
      belongs_to :user
      belongs_to :topic
      has_many :comments
    end
    

    我已经设置了资源映射,如下所示:

    map.resources :topics do |topic|
      topic.resources :articles
    end
    

    当我调用适当的url(例如 /:topic_slug/articles/2 )在我的文章视图中,我使用partial来处理文章的创建和编辑,如下所示:

    <% form_for(@article) do |f| %>
      ...
    <% end %>
    

    如果我试图创建一篇新文章或编辑一篇现有文章,则出现以下错误:

    NoMethodError in Articles#new
    
    Showing app/views/articles/_form.html.erb where line #1 raised:
    
    undefined method `articles_path' for #<ActionView::Base:0x103d11dd0>
    Extracted source (around line #1):
    
    1: <% form_for(@article) do |f| %>
    2:   <%= f.error_messages %>
    3: 
    4:   <p>
    Trace of template inclusion: app/views/articles/new.html.erb
    

    有人知道我做错了什么,我错过了什么吗?

    2 回复  |  直到 15 年前
        1
  •  4
  •   klew    15 年前

    您还需要传递主题:

    <% form_for([@topic, @article]) do |f| %>
    

    当你只经过 @article form_for 它试图根据 @文章 -这就是为什么你的错误说你没有 article_path 方法。当你经过的时候 [@topic, @article] 福尔摩亚 比你想打电话给它 topic_article_path .

    如果你没有 @topic 在创建新文章时,可能需要指定接受无主题文章的新路由,因此添加:

     map.resources :articles
    

    然后:

     <% form_for(@article) do |f| %> 
    

    会起作用,但它会生成如下URL: /articles/3 -没有主题部分。

        2
  •  0
  •   Dave Sims    15 年前

    如果需要项目的非嵌套路由,请分别映射项目:

    map.resources :articles