Rails: How do I create a default value for attributes in Rails activerecord’s model? [duplicate]

This question already has answers here: Rails: How can I set default values in ActiveRecord? (29 answers) Closed 8 years ago. I want to create a default value for an attribute by defining it in ActiveRecord. By default everytime the record is created, I want to have a default value for attribute :status. I tried … Read more

Rails find_or_create_by more than one attribute?

There is a handy dynamic attribute in active-record called find_or_create_by: Model.find_or_create_by_<attribute>(:<attribute> => “”) But what if I need to find_or_create by more than one attribute? Say I have a model to handle a M:M relationship between Group and Member called GroupMember. I could have many instances where member_id = 4, but I don’t ever want … Read more

What is causing this ActiveRecord::ReadOnlyRecord error?

This follows this prior question, which was answered. I actually discovered I could remove a join from that query, so now the working query is start_cards = DeckCard.find :all, :joins => [:card], :conditions => [“deck_cards.deck_id = ? and cards.start_card = ?”, @game.deck.id, true] This appears to work. However, when I try to move these DeckCards … Read more

delete_all vs destroy_all?

I am looking for the best approach to delete records from a table. For instance, I have a user whose user ID is across many tables. I want to delete this user and every record that has his ID in all tables. u = User.find_by_name(‘JohnBoy’) u.usage_indexes.destroy_all u.sources.destroy_all u.user_stats.destroy_all u.delete This works and removes all references … Read more

Case-insensitive search in Rails model

My product model contains some items Product.first => #<Product id: 10, name: “Blue jeans” > I’m now importing some product parameters from another dataset, but there are inconsistencies in the spelling of the names. For instance, in the other dataset, Blue jeans could be spelled Blue Jeans. I wanted to Product.find_or_create_by_name(“Blue Jeans”), but this will … Read more

Do rails rake tasks provide access to ActiveRecord models?

I am trying to create a custom rake task, but it seems I dont have access to my models. I thought this was something implicitly included with rails task. I have the following code in lib/tasks/test.rake: namespace :test do task :new_task do puts Parent.all.inspect end end And here is what my parent model looks like: … Read more