首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >UserController#welcome中的ActiveRecord::HasManyThroughAssociationNotFoundError

UserController#welcome中的ActiveRecord::HasManyThroughAssociationNotFoundError
EN

Stack Overflow用户
提问于 2010-01-31 08:46:26
回答 1查看 7.8K关注 0票数 18

我在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

EN

回答 1

Stack Overflow用户

发布于 2010-01-31 11:39:19

在使用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
票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2170108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档