【问题标题】:trying the rails model association尝试 Rails 模型协会
【发布时间】:2017-12-31 05:18:56
【问题描述】:

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

//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(country: "Japan", city: "Kyoto")

但我在位置 NoMethodError: undefined method `location' for #

我也应该在帖子中引用location:references type:references category:references

【问题讨论】:

  • 你有3个班级Category,让他们不同的名字。
  • 抱歉编辑了我刚刚复制粘贴
  • 请同时添加迁移文件。
  • 我已经解决了这个问题,是的,我所做的是我删除了每个都有一个

标签: ruby-on-rails model-associations


【解决方案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

你可以删除它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多