-2

I'm not sure if this a best practices in terms of association. Anyone can help me

//post,rb
class Post < ApplicationRecord
  belongs_to :user
  has_one :location, through: :user
  has_one :category, through: :user
  has_one :type, through: :user
end

//user.rb
class User < ApplicationRecord
  has_many :posts
end

//category.rb
class Category < ApplicationRecord
  belongs_to :post
end

//location.rb
class Location < ApplicationRecord
  belongs_to :post
end

//type.rb
class Typo < ApplicationRecord
  belongs_to :post
end

So the one of main goal of this are it's like User.posts.location,create(country: "Japan", city: "Kyoto")

but i get an error with location NoMethodError: undefined method `location' for #

also should i a references in post like location:references type:references category:references

Eric Luciano
  • 35
  • 1
  • 9

1 Answers1

1

You need to rename the classes like

#location.rb
class Location< ApplicationRecord
   belongs_to :post
end

#type.rb
class Type < ApplicationRecord
   belongs_to :post
end

Not need to

through: :user #=> this use for many to many relationship

You can remove this

fool-dev
  • 7,671
  • 9
  • 40
  • 54