【问题标题】:A small puzzle of Rails AssociationsRails 协会的一个小谜题
【发布时间】:2016-03-25 03:41:26
【问题描述】:

有 2 张桌子。一个是User(id,name,email),另一个是Student(id,who_id)。

我想用这种方式:

Student.find(id).name, Student.find(id).email

而不是:

User.find(student.who_id).name, User.find(student.who_id).email

获取数据。

我该怎么办?

顺便说一句,我不能以任何理由将who_id 更改为user_id


class User < ActiveRecord::Base
end

class Student < ActiveRecord::Base
end

【问题讨论】:

  • 给出这种用法的整个背景。

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4


【解决方案1】:

您可以在 Student 模型中添加 nameemail 方法,如下所示:

class Student < ActiveRecord::Base
  belongs_to :user, class_name: :User, foreign_key: 'who_id'

  def name
    user.name
  end

  def email
    user.email
  end
end

您也可以使用 Rail 的委托方法以更少的代码做同样的事情:

class Student < ActiveRecord::Base
  belongs_to :user, class_name: :User, foreign_key: 'who_id'
  delegate :name, to: :user
  delegate :email, to: :user
end

一旦你开始工作,而不是Student.find(id).name, Student.find(id).email(它将从数据库中获取数据两次),你应该这样做:

student = Student.find(id) #single call to the database
# get the properties from the previous database call
student.name 
student.email

【讨论】:

  • 是的,这是个好方法,但我在想我们是否可以创建双向模型连接,这样student.id会在user.id被销毁时自动删除。即添加dependent: :destroy。我们可以吗 ?谢谢!
  • 我认为这个问题涵盖了:stackoverflow.com/questions/15939799/…
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多