Rails模型中的class_name foreign_key [英] class_name foreign_key in Rails model

查看:97
本文介绍了Rails模型中的class_name foreign_key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这段代码。用户有很多答案。 :class_name和:foreign_key的目的是什么?

I recently come across this code. User has many Answer. What is the purpose of the :class_name and :foreign_key ?

class Answer < ApplicationRecord
    belongs_to :user, :class_name => 'Question", :foreign_key => 'question_id'
end


推荐答案

这里的命名有点奇怪,但是:class_name 的目的是允许您使用与Rails期望的类不同的类。当您在模型上具有 belongs_to:user 时,Rails希望它指向名为 User 的父类。在您的示例中,Rails跳过了查找 User 类的过程,而是查找了 Question 模型。

The naming here is kind of strange, but the purpose of :class_name is to allow you to use a class that is different from the one Rails expects. When you have a belongs_to :user on a model, Rails would expect that to point to a parent class called User. In your example, Rails skips looking for a User class and instead looks to the Question model.

但是,最常见的用法是使用非默认关联名称比使用默认名称更有意义,因此更合适的示例是当您使用用户模型和竞赛模型,其中每个竞赛都有一个用户作为获胜者,您可以每个竞赛属于 User ,但这并不具有表现力,相反,您可能希望将该关系称为 winner

The most common usage of this, though, is when a non-default association name makes more sense than the default. So a more apt example is when you have a User model and Competition model wherein each competition has one user as a winner. You could have each Competition belong to a User, but that wouldn't be as expressive. Instead you may want to have the relationship be referred to as winner:

class User < ActiveRecord::Base
  has_many :winners, class_name: "Competition", foreign_key: "competition_id"
end

class Competition < ActiveRecord::Base
  belongs_to :winner, class_name: "User", foreign_key: "winner_id"
end

这使您可以将用户称为赢家

This allows you to refer to users as winners:

competition = Competition.first
competition.winner

这要多得多比您编写 competition.user 更具表现力。

This is a lot more expressive than if you were to write competition.user.

这篇关于Rails模型中的class_name foreign_key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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