Note that there are some explanatory texts on larger screens.

plurals
  1. POTrouble building an ActiveModel in Ruby on Rails 3 using namespaces
    primarykey
    data
    text
    <p>I am using Ruby on Rails 3 and I am trying to build an ActiveModel <a href="https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb" rel="nofollow">this way</a>:</p> <pre><code>module Users # I use a namespace class Account extend ActiveModel::Naming extend ActiveModel::Translation include ActiveModel::Validations attr_accessor :name attr_reader :errors def initialize @errors = ActiveModel::Errors.new(self) end def validate! errors.add(:name, "can not be nil") if name == nil end # The following methods are needed to be minimally implemented def read_attribute_for_validation(attr) send(attr) end def Account.human_attribute_name(attr, options = {}) attr end def Account.lookup_ancestors [self] end def persisted? false end end </code></pre> <p>If in my controller I make this</p> <pre><code>def create @account = Users::Account.new @account.errors.add( :name, "can not be blank" ) ... end </code></pre> <p>I get this error:</p> <pre><code>undefined method `add' for nil:NilClass </code></pre> <p>If I make </p> <pre><code>@new_account = Users::Account.new </code></pre> <p>the debug of <code>@new_account</code> is</p> <pre><code>--- !ruby/object:Users::Account id: name: surname: updated_at: </code></pre> <p><strong>Where is the error and how can I solve that?</strong></p> <hr> <p>P.S.: I don't want to use <code>validate_presence_of</code> because I need a different validation process, but I think that also that method doesn't work.</p> <hr> <p>If I use the <code>validate!</code> method I get the following error that refers to that</p> <pre><code>NoMethodError in Users/accountsController#create You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]= Application trace pp/models/users/account.rb:16:in `validate!' </code></pre>
    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