开发者

Polymorphic many-to-many association error in Ruby On Rails 3

I am struggling with a polymorphic many-to-many association in rails 3.

My Article model looks like this:

class Article < ActiveRecord::Base
  has_many :article_tags
  has_many :people, :through => :article_tags, :source => :taggable, :source_type => :person
end

My ArticleTag model looks like this:

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

My Person model looks like this:

class Person < ActiveRecord::Base
  has_many :article_tags, :as => :taggable
end

Finally, my Organization model looks like this:

class Organization < ActiveRecord::Base
  has_many :article_tags, :as => :taggable
end

I have a schema which looks like this:

ActiveRecord::Schema.define(:version => 20110322234836) do

  create_table "article_tags", :force => true do |t|
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "articles", :force => true do |t|
    t.string   "title"
    t.text     "content"
    t.date     "published_on"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "people", :force => true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "organizations", :force => true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

I was hoping that this would allow me to create people and organizations relationships from my articles like this:

Article.create!
Article.first.people.create!

and hopefully to be able to access it the other way afterwards by

Person.first.articles

Unfortunately I get an error when I try to add a person this way:

Article.first.people.create!

NameError: uninitialized constant Article::person
.../base.rb:1199:in `compute_type'
.../reflection.rb:162:in `klass'
.../association_collection.rb:157:in `transaction'
.../has_many_through_association.rb:41:in `create_record'
.../has_many_through_association.rb:13:in `create!

Any help would be very much appreciated I've tried开发者_开发问答 many alternatives but with no success.


I actually just had to some something similar to this recently. It looks like most of your code is right although in mine for the first section I would try changing do this:

class Article < ActiveRecord::Base
  has_many :article_tags
  has_many :people, :through => :article_tags, :source => :taggable, :source_type => "Person"
end

Also you can't do: Article.first.people.create({:name => "Tim"}) You would have to assign it to a variable first:

article = Article.first
article.people.create({:name => "Tim"})

Let me know if this works for you. I just skimmed through. If it doesn't i can double check my code again and see if there are any other differences.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜