Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a :class_name with a string or a symbol in Rails 3

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

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?

like image 868
Justin Avatar asked Dec 19 '25 21:12

Justin


1 Answers

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.

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.

like image 51
DigitalRoss Avatar answered Dec 22 '25 13:12

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!