0

I want to make user to have only one matriculation per user. However I get error "undefined method `matriculations' for nil:NilClass". How could I make it work? (I use devise as user auth if its matter).

 def matriculation_limit
  if self.user.matriculations(:reload).count <= 1
    errors.add(:base, "Yuo already have one matriculation form")
  else
    redirect_to new_matriculation_path
  end
 end

2 Answers2

1

With a has_one association, then the association finder method is singular like @user.matriculation, not @user.matriculations. And there's no point counting them because there will only be one.

Regarding comment:

You don't need to check anywhere how many matriculations the user has, because it's a singular association, so you'll just be updating the association (changing the ID in the foreign key column matriculation_id in the users table)

class User < ActiveRecord::Base
  has_one :matriculation, :class_name => "User", :foreign_key => "matriculation_id"
end

class Matriculation < ActiveRecord::Base
  belongs_to :user
end

# some controller action...
  @user.matriculation = Matriculation.find(params[:matriculation_id]) # or something!
Mike Campbell
  • 7,921
  • 2
  • 38
  • 51
  • Did try to correct create or update action with no success. I'm getting error "Couldn't find Matriculation without an ID". It returns nil, because can't find ID?! Have little understanding how to show ID! –  May 09 '13 at 15:18
0

self.user == user_object.user. And seems like you dont have method user for class user. ANd another things, you have has_one, so you have to use self.matriculation

so correct would be

if self.matriculation
    errors.add(:base, "Yuo already have one matriculation form")
  else
    redirect_to new_matriculation_path
  end
Avdept
  • 2,261
  • 2
  • 26
  • 48
  • `self.matriculation.count` will cause an exception because a Matriculation object will be returned, and that won't have a `count` method. – Mike Campbell May 08 '13 at 18:53