问题
I have the following models:
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :first_name, :use => :slugged
has_one :professor
after_create :create_professor
def create_professor
self.professor = Professor.create
end
end
class Professor < ActiveRecord::Base
extend FriendlyId
friendly_id :first_name, :use => :slugged
belongs_to :user
def first_name
user.first_name
end
end
At the time that create_professor
is called and therefore the execution passes to the Professor model (self.professor = Professor.create
), when it gets to try to create the slug in this method:
def first_name
user.first_name
end
I get an undefined method first_name for nil:NilClass
, so it seems the Professor object doesn't know what is his associated user.
Any tips on how to solve this?
回答1:
You don't need:
def create_professor
self.professor = Professor.create
end
Since create_professor is created by your association.
来源:https://stackoverflow.com/questions/11488700/friendly-id-using-value-from-belongs-to-association