开发者

Ruby on Rails: How do you seed the *_type column in polymorphic models?

I have a lot of data that I'm trying to seed into a polymorphic model in Rails 2.3.8. The association for all of the data is with the County model. The data looks like:

data = Datum.create([
  ...
  { :value => '14389', :value_type => County, :value_id =>'3103'},
  { :value => '59013', :value_type => County, :value_id =>'3105'},
  { :value => '17117', :value_type => County, :value_id =>'3106'},
  ...
])

The :value_type => County values lead to "undefined method `base_class' for String:Class."

I have tens of thousands of these values that I would like to seed into the database. They are similar to the values above except some are associated with the County model, some with the State model, and some with the City model. They are static values that will not be edited after seeding into the database.

How do I seed the model into the :value_type field?

(or... am I approaching this incorrectly and if so, how would you approach it?)

Edit: The relevant part of the schema.rb file:

Isaac -

create_table "data", :force => true do |t|
  t.integer  "value"
  t.string   "value_type"
  t.integer  "value_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "counties", :force => true do |t|
  t.string   "name开发者_如何学C"
  t.integer  "state_id"
  t.integer  "ansi_code"
  t.string   "ansi_class"
  t.datetime "created_at"
  t.datetime "updated_at"
end

I tried the following on the seeding, too, and it didn't work (County in quotes):

{ :value => '14389', :value_type => 'County', :value_id =>'3103'},


You definitely don't need the "value" column in your schema -- just "value_id" and "value_type". Then your seed data should look like this:

...
{ :value_id => 12345, :value_type => "County" },
...

Note that "County" is a string in quotes.

Another alternative would be to do this:

{ :value => County.find(12345) }

And then Rails will automatically set the :value_type and :value_id columns for you based on the class name and id of the County record. This example might give you a better idea of what's going on. However, for thousands of records this would be much slower, so the first approach is probably better for this case.


This is happening because you've done this in your model:

belongs_to :value, :polymorphic => true

And because you're trying to set the value column on the table too. Rails will not be able to tell the difference between you setting the association or the column via this method. To set the column use this:

self[:value] = "something"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜