简体   繁体   中英

Rails belongs_to association on model name that has underscores

Hey guys I broke a bit of rails convention by using underscores instead of camelcasing on a class name (Ui_1_Log instead of Ui1Log) and now when I refer to the association it isnt finding the right class. For example:

class Ui_1_Log < ActiveRecord::Base
  belongs_to :account
end

class Account < ActiveRecord::Base
  has_many :ui_1_logs
end

Now when I call the association in the rails console it doesnt work because it returns a classname as Camelcase when it needs to keep the underscores...

x = Account.first
x.ui_1_logs.first  #returns nameError: uninitialized constant Account::Ui1Log 

It needs to be Account::Ui_1_Log but I don't know how to force that...Any ideas?!

You can set the class name on the association with class_name option.

class Account < ActiveRecord::Base
  has_many :ui_1_logs, class_name: 'Ui_1_Log'
end

But I still recommend to follow conventions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM