tfantina
tfantina

Reputation: 815

Problems setting up an association in Rails

I have a Post model and a User model. Users can love posts, this information is kept in a separate Love model rather than directly on the post because the User has to be able to see a record of the post's they've liked.

I have a migration like this:

    create_table :loves do |t|
      t.references :post, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true
    end

User.rb

  has_many :loves

Post.rb

  has_many :loves

Love.rb

class Love < ApplicationRecord
  belongs_to :user
  has_one :dinner
end

This association does not seem to work, whenever I try to love a post I get this error:

uninitialized constant User::Lofe 

I realize the word "Lofe" may seem like a typo of Love, which is what I thought but I've searched through the entire codebase and there is no instance of Lofe.

In Rails console if I type User.first.love I will get an error suggesting Did you mean? loves this seems to indicate that the association exists (works with both Users and Dinners) but if I then type User.first.loves it will throw the same Uninitialized constant error.

Upvotes: 1

Views: 60

Answers (1)

MurifoX
MurifoX

Reputation: 15109

I did a little research and the problem is with Rails inflection engine. As you can see here: https://twitter.com/andypike/status/578214888465657856 and here: https://rails.lighthouseapp.com/projects/8994/tickets/2407-inflector-singularising-loves-to-lofe-but-pluralizing-love-to-loves apparently when using the word love you need to configure it by hand in config/initizers/inflections.rb

Upvotes: 6

Related Questions