开发者

How can I store the object `id` in a migration file?

I'm using Ruby on Rails 3.0.7 and MySQL 5.1. I'd like to force to store the object id in a migration file. For example I have this:

User.create!(
  :name => 'Test name'
)

but I would like to do something like this:

User.create!(
  :id   => '12345', # Force to开发者_Go百科 store the object data with id '12345'
  :name => 'Test name'
)

Note: the above code will not force the id value in the database.

Is it possible? If so, how?


You can't mass assign the restricted fields like id. But you can individually set them:

user = User.new(:name => 'Test name')
user.id = 12345
user.save!

OR

User.create!(:name => 'Test name') do |user|
  user.id = 12345
end


You can indeed mass-assign protected fields. Here's how to do it. In your model define the following:

def attributes_protected_by_default
  default = [ self.class.inheritance_column ]
end

What you are doing here is overriding the base method:

# The primary key and inheritance column can never be set by mass-assignment for security reasons.
def self.attributes_protected_by_default
  default = [ primary_key, inheritance_column ]
  default << 'id' unless primary_key.eql? 'id'
  default
end

...to include only the inheritance_column excluding the id, or primary_key column. At this point you can now mass-assign the ID for that model.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜