gpt4 book ai didi

ruby-on-rails - ActiveRecord::HasManyThroughAssociationNotFoundError 在 UserController#welcome

转载 作者:行者123 更新时间:2023-12-03 13:21:49 26 4
gpt4 key购买 nike

我在rails中有一个多对多的关系。所有数据库表都相应地适当命名。所有模型文件都是复数并使用下划线分隔单词。所有命名约定都遵循 ruby​​ 和 rails 标准。我在我的模型中使用了很多,如下所示:

has_many :users, :through => :users_posts #Post model
has_many :posts, :through => :users_posts #User model
belongs_to :users #UsersSource model
belongs_to :posts #UsersSource model

这个错误还有什么可能来自?
ActiveRecord::HasManyThroughAssociationNotFoundError in UsersController#welcome
Could not find the association :users_posts in model Post

最佳答案

使用 has_many :through 时需要将连接模型定义为单独的关联。 :

class Post < ActiveRecord::Base
has_many :user_posts
has_many :users, :through => :user_posts
end

class User < ActiveRecord::Base
has_many :user_posts
has_many :posts, :through => :user_posts
end

class UserPost < ActiveRecord::Base
belongs_to :user # foreign_key is user_id
belongs_to :post # foreign_key is post_id
end

当您需要保留与连接模型本身相关的数据时,或者如果您想对连接执行与其他两个模型分开的验证时,这种方法效果最佳。

如果你只想要一个简单的连接表,使用旧的 HABTM 语法会更容易:
class User < ActiveRecord::Base
has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
has_and_belongs_to_many :users
end

关于ruby-on-rails - ActiveRecord::HasManyThroughAssociationNotFoundError 在 UserController#welcome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2170108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com