我不确定这是否是关联方面的最佳做法。任何人都可以帮助我
//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
所以这就是它的主要目标之一 User.posts.location,create(国家:“日本”,城市:“京都”)
但我收到位置NoMethodError的错误:#
的未定义方法`location'我也应该在location:references type:references category:references
答案 0 :(得分:1)
您需要重命名类
#location.rb
class Location< ApplicationRecord
belongs_to :post
end
#type.rb
class Type < ApplicationRecord
belongs_to :post
end
不需要
through: :user #=> this use for many to many relationship
您可以删除此