ruby on rails - Limit create action to 1 post per user -
i want make user have 1 matriculation per user. error "undefined method `matriculations' nil:nilclass". how make work? (i use devise user auth if matter).
def matriculation_limit if self.user.matriculations(:reload).count <= 1 errors.add(:base, "yuo have 1 matriculation form") else redirect_to new_matriculation_path end end
with has_one
association, association finder method singular @user.matriculation
, not @user.matriculations
. , there's no point counting them because there one.
regarding comment:
you don't need check anywhere how many matriculations user has, because it's singular association, you'll updating association (changing id in foreign key column matriculation_id
in 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 # controller action... @user.matriculation = matriculation.find(params[:matriculation_id]) # or something!
Comments
Post a Comment