Nezir
Nezir

Reputation: 6915

Rails model associations naming conventions

I have model User:

class User < ApplicationRecord
  has_many :selfies
  has_many :likes
  has_many :comments

also, have model Selfie:

class Selfie < ApplicationRecord
  belongs_to :user
  has_many :likes, dependent: :destroy
  has_many :comments, dependent: :destroy

also, have model Comment:

class Like < ApplicationRecord
  belongs_to :user
  belongs_to :selfie

In my code I can normally use like some instance @user.comments.count and I am getting number, but when try to use @user.selfies.count I am getting error

NameError: uninitialized constant User::Selfy

What am I doing wrong here? I was thinking its something about naming conventions but I tried some combinations, selfy selfys selfie ...

Upvotes: 0

Views: 394

Answers (2)

Tai
Tai

Reputation: 1254

Try in rails console:

"selfies".singularize # -> "selfy"

So that, Rails detect wrong model class. You can do as suggestion of @guitarman but anywhere you use selfies you have to do that.

Another way is to create the map between plural and singular of selfies. Create config/initializers/selfies_inflection.rb and add the map:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'selfie', 'selfies'
end

Upvotes: 3

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You need to rename your model(and table if need) to Selfy, check this example of what the Rails doing under the hood:

$> bundle exec rails console
# convert to table name
"Selfy".tableize 
=> "selfies"
# singular
"selfies".singularize
=> "selfy"
# plural
"selfy".pluralize
=> "selfies"

Your AR model must be:

class Selfy < ApplicationRecord
end
class Like < ApplicationRecord
  belongs_to :user
  belongs_to :selfy
end
class User < ApplicationRecord
  has_many :selfies
end

Upvotes: 2

Related Questions