sco*_*ott 18 activerecord many-to-many ruby-on-rails associations has-many-through
我在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
zet*_*tic 38
使用时,您需要将连接模型定义为单独的关联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
| 归档时间: | 
 | 
| 查看次数: | 7478 次 | 
| 最近记录: |