【问题标题】:Friendly_id using value from belongs_to associationFriendly_id 使用来自 belongs_to 关联的值
【发布时间】:2012-07-15 01:29:14
【问题描述】:

我有以下型号:

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

在调用 create_professor 并因此执行传递给教授模型 (self.professor = Professor.create) 时,它会尝试在此方法中创建 slug

def first_name
  user.first_name 
end

我得到了一个undefined method first_name for nil:NilClass,所以教授对象似乎不知道他的关联用户是什么。

关于如何解决这个问题的任何提示?

【问题讨论】:

  • 试试self.professor.create而不是self.professor = Professor.create

标签: ruby-on-rails associations friendly-id after-create


【解决方案1】:

你不需要:

  def create_professor
    self.professor = Professor.create 
  end

因为 create_professor 是由您的协会创建的。

【讨论】:

  • 我按照上述步骤操作,但出现错误 - 找不到 id=xyz 的配置文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多