使用值Friendly_id从belongs_to的关联 [英] Friendly_id using value from belongs_to association

查看:190
本文介绍了使用值Friendly_id从belongs_to的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

 类用户< ActiveRecord的::基地
  延长FriendlyId
  friendly_id:FIRST_NAME,:使用=> :猛击  HAS_ONE:教授
  after_create:create_professor  高清create_professor
    self.professor ​​= Professor.create
  结束结束一流的教授,LT; ActiveRecord的::基地
  延长FriendlyId
  friendly_id:FIRST_NAME,:使用=> :猛击  belongs_to的:用户
  高清FIRST_NAME
    user.first_name
  结束结束

在该 create_professor ​​调用;因此,执行传递到教授的模型( self.professor ​​= Professor.create ),当它到达尝试这种方法来创建蛞蝓

 高清FIRST_NAME
  user.first_name
结束

我得到一个的零未定义的方法FIRST_NAME:NilClass ,如此看来教授对象不知道什么是自己的相关用户

如何解决这个任何提示?


解决方案

您不需要

 高清create_professor
    self.professor ​​= Professor.create
  结束

由于create_professor是由您的关联创建。<​​/ P>

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?

解决方案

You don't need:

  def create_professor
    self.professor = Professor.create 
  end

Since create_professor is created by your association.

这篇关于使用值Friendly_id从belongs_to的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆