尝试rails模型关联

问题描述 投票:-2回答:1

我不确定这是否是关联方面的最佳做法。任何人都可以帮助我

//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:references type:references category:references这样的帖子中引用

ruby-on-rails model-associations
1个回答
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

你可以删除它

© www.soinside.com 2019 - 2024. All rights reserved.