0

Hi I have a rails app which has a table called "listings". This table has a column called "city". But the column has no data right now, everything is null. Id like to add the string: "Not Available" to column values for all the rows in this table. How can I do that?

I tried using sql to add it directly to the DB and it wouldn't work.

So I guess I must use the rails migration commands to achieve this. but I cannot find the exact command. I know its something like this....

rails generate migration ??

Can someone give me a hand?

Thanks

1 Answer 1

2

Before telling you how to actually do this with Rails, I would ask you to consider hard coding this sort of presentation logic to your database schema. You could do this at the model level, and just overwrite the accessor for this field.

def city
  read_attribute("city") || "Not Available"
end

Putting this information into the database can cause issues. For example, you'll no longer be able to quickly tell which rows have a default value for city.

If you do decide you want to do this, in a migration, add:

change_column :listings, :city, :default => "Not Available"
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot for your help. Yes, Im learning rails and this is my development environment. I will follow your advice when I create the model for production. right now, I just need these values in to test features that depend on those values.
Keep in mind, if you add this migration, the default value for your production environment will also be "Not Available"
Hi there. I ran the following command for migration:"rails generate migration change_column :listings, :city, :default=> "Not Available". This worked, then I added: "rake db:migrate". It gave me errors saying that the table "listings" already exists. It was trying to create a table with the name "listings" instead of altering the existing table. Any suggestions?
Here are the first few lines of the console output with the error: == CreateListings: migrating ================================================= -- create_table(:listings) rake aborted! An error has occurred, this and all later migrations canceled:
Just run rails genearte migration SetDefaultForCityInListings. This will create a file in ./db/migrate called set_default_for_city_in_listings_[timestamp]. Then, modify that file to include the line above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.