Friendly_id using value from belongs_to association

走远了吗. 提交于 2019-12-23 09:49:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!