在Rails 3中使用字符串或符号定义:class_name

时间:2021-09-14 10:57:56

If I have a Invitation model and a User model, with the Invitation model having a requester_id column, why does this work,

如果我有一个邀请模型和一个用户模型,邀请模型有一个requester_id列,为什么这样做,

class Invitation < ActiveRecord::Base
  belongs_to :requester, :class_name => "User"
end

and this doesn't work?

这不起作用?

class Invitation < ActiveRecord::Base
  belongs_to :requester, :class_name => :user
end

In general, when do I use symbols, and when do I use strings in Rails 3?

一般来说,我何时使用符号,何时在Rails 3中使用字符串?

2 个解决方案

#1


2  

Either One

You would certainly need :User, not :user.

你当然需要:用户,而不是:用户。

The core Ruby Symbol defines a #to_s and String defines a #to_sym, so in any Ruby context you may often substitute one for another.

核心Ruby符号定义了#to_s,String定义了#to_sym,因此在任何Ruby上下文中,您可能经常将一个替换为另一个。

I might be tempted to say: when in doubt, follow the Rails3 API documentation. except it doesn't say, although the example uses a string. But in this case, it works, you can safely use a symbol.

我可能会说:如有疑问,请遵循Rails3 API文档。除了它没有说,虽然该例子使用了一个字符串。但在这种情况下,它可以工作,你可以安全地使用符号。

#2


0  

Remember that it is case sensitive. So :User may work. In any case, I would use a string as that's what it says in the docs :)

请记住,它区分大小写。所以:用户可以工作。在任何情况下,我会使用一个字符串,因为它是在文档中说的:)

#1


2  

Either One

You would certainly need :User, not :user.

你当然需要:用户,而不是:用户。

The core Ruby Symbol defines a #to_s and String defines a #to_sym, so in any Ruby context you may often substitute one for another.

核心Ruby符号定义了#to_s,String定义了#to_sym,因此在任何Ruby上下文中,您可能经常将一个替换为另一个。

I might be tempted to say: when in doubt, follow the Rails3 API documentation. except it doesn't say, although the example uses a string. But in this case, it works, you can safely use a symbol.

我可能会说:如有疑问,请遵循Rails3 API文档。除了它没有说,虽然该例子使用了一个字符串。但在这种情况下,它可以工作,你可以安全地使用符号。

#2


0  

Remember that it is case sensitive. So :User may work. In any case, I would use a string as that's what it says in the docs :)

请记住,它区分大小写。所以:用户可以工作。在任何情况下,我会使用一个字符串,因为它是在文档中说的:)