2012-02-07 44 views
0

我看过很多教程,以及如何在rails中创建多态关联但不能使其工作。截至目前,我下面就多态关联Ryan Bates tutorial,我不断收到对多义关联导轨缺少路径助手3

错误未定义的方法我一个试图标签添加到我的博客文章,不想使用插件

我收到错误

undefined method `tags_path' for <class> 

的routes.rb

resources :blog do 
    resources :tags 
end 

_form.html.erb标签为

<%= form_for([@taggable, @tag]) do |f| %> 

<div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
</div> 
<div class="actions"> 
    <%= f.submit %> 
</div> 

tag.rb

class Tag < ActiveRecord::Base 
    belongs_to :taggable, :polymorphic => true 
end 

blog.rb

class Blog < ActiveRecord::Base 
    has_many :tags, :as => :taggable 
end 

迁移文件

class CreateTags < ActiveRecord::Migration 
    def self.up 
    create_table :tags do |t| 
     t.string :name 
     t.string :taggable_type 
     t.integer :taggable_id 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :tags 
    end 
end 

tags_controller.rb

def index 
    @taggable = find_taggable 
    @tags = @taggable.tags 
    end 

    def find_taggable 
     params.each do |name, value| 
      if name =~ /(.+)_id$/ 
       return $1.classify.constantize.find(value) 
      end 
     end 
     raise ActiveRecord:NoRecord.new("Couldn\'t find it captain!") 
    end 
+0

Rails的是什么版本的?这篇教程已经快三年了,这在Rails时代已经很长时间了。我所知道的最好的指南是[Rails Guide](http://guides.rubyonrails.org/association_basics.html),它涵盖了多态关联,但值得一读的是它的(简短)整体。 – 2012-02-07 02:29:31

+0

rails 2.另外我知道它是旧的,但其中一些概念与rails 3中的一样,只是试图找出错误出现的原因。生病检查你已经发送的链接我只在目前的轨道api中查找 – coletrain 2012-02-07 02:38:23

回答

1

你可以使用一个polymorphic_url,details

polymorphic_url([@blog, @tag]) 

或只使用一个标签的宝石一样https://github.com/mbleigh/acts-as-taggable-on

+0

是在你的控制器中定义的@taggable,因为如果它是零,也会发生同样的情况。 – nodrog 2012-02-07 02:41:06

+0

如果我使用上述我将无法添加标签照片视频等。是@taggable是在我的控制器中定义。我上面更新了我的代码。 – coletrain 2012-02-07 02:52:23

+0

想通了。在我的控制器中,我需要在@tag = Tag.new上面添加@taggable = find_taggable,并且一切正常。 – coletrain 2012-02-07 03:57:50