Initialize database values in rails - ruby-on-rails

In my project, i have a situation like when user runs the application.
The system should insert some values in a table which is used allover the application.
(These value should be inserted only once when the project is executed at first time)
I am trying to find out if there is any initialization function like Constructors in Rails.
I tried to use the config/application.rb, but i am not sure its the right way to do this.
Please suggest.
Thanks

If you looking for inserting some default dictionary data like month names etc you should look into seed.rb file or even better consider using seed_fu gem (https://github.com/mbleigh/seed-fu)

Yes you can insert/edit/delete records into table with migration :
1) Create the migration .
2) Run db query inside the execute. like :
execute "insert into users (name, role) values ('vik', 'admin')"
3) After all the insertion operation run the migration.

How if you update have boolean field or any kind of integer field to maintain status in your application. And for the very first time, user runs the application, your code will insert necessary values for that user in db and update boolean/status field and will be cached(for better performance only rather than fetching value from db every time). However after every time cache is cleared, it will send the query to db; but fetching boolean value(checking user status) is more faster than checking all inserted values for that user.

Related

How to keep track of a table data-change migration on Ruby on Rails

Here is the problem:
I have Ruby on Rails project that has a table that have almost 100k rows and I have a binary column and I want to make changes in the content data on this column.
So I must iterate over those 100k rows, making changes on that row on particular column, saving it back on database.
But I must keep track of changes because these changes could fail and I should have someway to re-start data change from where I stopped.
Here is what I thought of a way of doing it:
Create a Migration to have a table MigrationTrack to track all records that have being migrated
Create a model of the above migration
Create a rake task that grabs all 100k from TableToUpdate and iterate over them, saving data back to row and save its ID on MigrationTrack. Create a logic to have a join on TableToUpdate and MigrationTrack to filter only ids that I haven't updated yet
After above migration finished create another migration to drop MigrationTrack table and remove its model.
Is there any other "Railsh way" to do that? Anyone have done such change?
Thanks
I would do it like this:
Add and deploy a migration adding a new column with the desired data type to the database table.
Add code to your model that save the value from the old column into the new column too.
Run a rake task or a simple one-liner in the console that touches all records to make sure the code introduced in step one ran on each record.
After this step, you can manually verify if all records in the database have both columns set as expected.
Switch using the new attribute instead of the old attribute in the code.
Drop the old column.
For simple cases, try running a simple view to check how it will turn out to be, for example, if your migration is
change_column :table, :boolean_field, 'integer USING CASE boolean_field THEN ...'
then you try do a simple select query with your cast, if you need more safey, you can create 'up' and 'down' methods on your migrations, then you can create a backup table on up, and on down, you can revert the values

Does ActiveRecord cache table_name?

I've got an ActiveRecord class that needs to look at two different tables depending on a configuration switch, so I'm planning to do the following:
def table_name
config_is_on? ? :table1 : :table2
end
I'm wondering whether the table_name method is always called when queries are run against this model: the application is not going to be restarted when the configuration changes, so this value cannot be cached.
Does ActiveRecord always evaluate the table_name or just once during application startup / initialization? If it's cached how do I force it to evaluate table_name every time?
Not only the table name, also the column definition. You'd better go with a schema setup like with the Apartment gem. Depending on some state of a request, the actual table search path in the database is set to something. So you can do two schemas, one with the first table, one with the second (the rest of tables may be on just one schema) and changing the search path you will get different data.

Rails reset single column

I am trying to implement a rake task that will run once a month to reset a single column. I would prefer to reset the column to its default value but I cannot find any methods to help me accomplish this. reset_column_information does not work
What is the most efficient way to reset a single column in active record?
Base method #update_all does the update direct in the database, so it is very efficient. However it bypasses callbacks because the models aren't loaded: http://apidock.com/rails/ActiveRecord/Base/update_all/class
SomeModel.update_all("some_column = 4"); # sets all some_column attributes to 4
Resetting it to the default depends on how you are setting the default in the first place. If the default is calculated in the model, then you would have to select and instantiate all the records, which could be very slow. If it's defined in the database, maybe it would be possible but I think it would be database specific.
If you're hardcore you can also drop the column(s) in a migration and then recreate it/them. Sometimes this will be a lot faster. I wouldn't do it in a critical application automatically - but if you're fiddling with your own local machine and just want to test stuff quick, this can be effective.

Scaffolding user ID resetting

in the application i am currently creating in ruby on rails. I am trying to do some tests in rails console where i have to destroy data in the database and the database is connected to a server. I am importing an XML and parsing it and putting it into a database with scaffolding.
Now what i need: Basically what i am attempting to do is to destroy the data and replace it with a new one every week..but the problem i am getting, the userid is gone up to 700+ and there are only 50 records :S cause it doesnt reset...
To delete all records i am currently using "whatever.destroy_all" does the trick
Any help?
Btw i am using SQLITE
The ID column created in the table usually is set as unique and to increment by 1 for each new record, which is why each time you destroy and add new data the ID keeps getting higher.
The fact that the ID # is getting larger and larger is not an issue at all.
If you really want to start back at zero, I would think you could drop the table and recreate it, but that seems like overkill for a trivial issue.
Regarding the connection to the other scaffold, how are you connecting the two and what do they both represent?
Ideally the data population for testing should be done through fixtures (or easy tools such as factorygirl etc..)
The main advantage of having a fix data set is you can run your tests in any environment. But as per your requirement you can do something like this,
When you populate the date through the active records pass the id parameter as well
Ex: User.new(:id => 1, :name => "sameera").create
By this way you can have constant id's But make sure you increment the id accordingly.

How can I cache Model objects in Rails?

Is there a technique that I can use in Rails so that whenever a simple "find" is performed on a Model object, memcached is first searched for the result, only if no result is found will a query by then made to the database?
Ideally, I'd like the solution to be implicit, so that I can just write Model.find(id), it first checks the cache and if a database query is required that the object returned is then added to the cache i.e. I don't need to wrap the Model.find(id) with additional code to check the cache for matching contents.
Thanks!
http://github.com/ngmoco/cache-money is the way to go

Resources