Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Ruby on Rails, how do I assign a default value to a member_of member of an ActiveRecord object?
    primarykey
    data
    text
    <p>I'm new to ruby on rails, and I've inherited a codebase. Right now I can't create a new user account in my application, when I try I get the following error:</p> <p>NoMethodError in Users::RegistrationsController#create</p> <p>undefined method `name' for nil:NilClass Rails.root: /home/nathan/dev/legwork-core</p> <p>Application Trace | Framework Trace | Full Trace app/models/contact.rb:74:in <code>block (2 levels) in &lt;class:Contact&gt;' app/models/user.rb:31:in</code>update_contact'</p> <p>The calling code is here:</p> <pre><code> searchable do string :category do self.category.name end end </code></pre> <p>Category is supposed to be an instance of ContactCategory, and what I think I need is to set self.category to the default if its nil. I tried this to fix it:</p> <pre><code> after_initialize :set_defaults def set_defaults self.category = ContactCategory.first if self.category.nil? end </code></pre> <p>I also tried:</p> <pre><code> def after_initialize self.category = ContactCategory.first if self.category.nil? end </code></pre> <p>And I've tried:</p> <pre><code> before_create :set_defaults def set_defaults self.category = ContactCategory.first if self.category.nil? end </code></pre> <p>Someone else has suggested putting this logic in before_save, but there is already a before_save that has this logic in it, that's where I saw what the author had intended to be the default in the first place.</p> <p>UPDATE:</p> <p>This question is silly now that I see what's wrong. I was assuming that the assignment statement never ran because I assumed ContactCategory.first was also not nil. Sadly, everything here is working as expected. The moral of the story is:</p> <p>All of the hooks I was using to set the default were working correctly. I would recommend using them to set a default using ActiveRecord.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload