Search code examples
ruby-on-railsassociationsmodels

association between three models


good day in this working association that I'm trying to do, using nested_form

#_form.html.erb in post
<%= f.fields_for :addresses do |address| %>
  <% address.association :state  %>
<% end %>

class Post < ApplicationRecord
  has_many :addresses, as: :addressable, dependent: :destroy
  accepts_nested_attributes_for :addresses, allow_destroy: true
end



class Address < ApplicationRecord
  belongs_to :states
  belongs_to :addressable, :polymorphic => true
end

class State < ApplicationRecord
  has_many :addresses  
end

print the error: Association :state not found!!! help me!


Solution

  • From the docs:

    class Book < ApplicationRecord
      belongs_to :author
    end
    

    belongs_to associations must use the singular term. If you used the pluralized form in the above example for the author association in the Book model, you would be told that there was an "uninitialized constant Book::Authors". This is because Rails automatically infers the class name from the association name. If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.

    So you must replace the line:

    belongs_to :states
    

    with

    belongs_to :state