例如,用户A可以属于T1和T2队. T1和T2队可以分别有四个不同的教练,一个教练是共同的.我希望能够通过简单地说:
u = User.find(1)coaches = u.coaches
以下是我的迁移脚本以及模型中的关联.我在设计中做错了吗?我的协会是否正确?
class createusers < ActiveRecord::Migration def self.up create_table :users do |t| t.column :login,:string,:default => nil t.column :firstname,:default => nil t.column :lastname,:default => nil t.column :password,:default => nil t.column :security_token,:default => nil t.column :token_expires,:datetime,:default => nil t.column :legacy_password,:default => nil end end def self.down drop_table :users endendclass CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.column :name,:string end end def self.down drop_table :teams endendclass TeamsUsers < ActiveRecord::Migration def self.up create_table :teams_users,:ID => false do |t| t.column :team_ID,:integer t.column :user_ID,:integer t.column :joined_date,:datetime end end def self.down drop_table :teams_users endend
以下是模型(不是整个文件):
class User < ActiveRecord::Base has_and_belongs_to_many :teams has_many :coaches,:through => :teamsclass Team < ActiveRecord::Base has_many :coaches has_and_belongs_to_many :usersclass Coach < ActiveRecord::Base belongs_to :teamsend
当我试图拉扯教练时会发生这种情况:
u = User.find(1)=> #<User ID: 1,firstname: "Dan",lastname: "Wolchonok">>> u.coachesActiveRecord::StatementInvalID: MysqL::Error: #42S22UnkNown column 'teams.user_ID' in 'where clause': SELECT `coaches`.* FROM `coaches` INNER JOIN teams ON coaches.team_ID = teams.ID WHERE ((`teams`.user_ID = 1))
这是sql中的错误:
MysqL ::错误:#42S22UnkNown列’teams.user_ID’在’where子句’中:SELECT coaches.* FROM教练INNER JOIN团队ON coaches.team_ID = teams.ID WHERE((teams.user_ID = 1))
我错过了我的:through子句吗?我的设计完全关闭了吗?有人能指出我正确的方向吗?
解决方法 你不能连续两次做一个has_many:它会告诉你它是一个无效的关联.如果你不想像上面那样添加finder_sql,你可以添加一个模仿你想要做的事情的方法.def coaches self.teams.collect do |team| team.coaches end.flatten.uniq end总结
以上是内存溢出为你收集整理的ruby-on-rails – Activerecord协会问题:获得has_many:通过工作全部内容,希望文章能够帮你解决ruby-on-rails – Activerecord协会问题:获得has_many:通过工作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)