So how do we go about doing this? Simple. First, set the primary key in the Model object to be the column in the table (since ActiveRecord always assumes primary key is a column called "id"). If we just run this and try to save the model object by firing up the rails console, rails gives an error saying there are no attributes "col1". This is because, rails assumes that the primary key is not editable. So all we have to do is define attributes for the primary key column col1. The overall changes are shown below:
class MyModel < ActiveRecord::Base
set_primary_key "col1"end
def col1
read_attribute "col1"
end
def col1=(value)
write_attribute "col1", value
end
Now fire up the rails console and create and save the model object, setting values for the required columns. Voila!
Note: since you are departing a bit from rails convention of primary keys, you will need to make sure that the required validations are added in the model so that you dont get errors from the database.
No comments:
Post a Comment