Rails嵌套在连接表上的where子句

时间:2014-02-25 22:26:02

标签: ruby-on-rails activerecord

我有两个通过连接表关联的模型。这是架构...

  create_table "group_shots", :force => true do |t|
    t.integer  "shot_id"
    t.integer  "group_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "groups", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "shots", :force => true do |t|
    t.string   "name"
    t.integer  "comedian_id"
    t.string   "pic_file_name"
    t.string   "pic_content_type"

在我的小组控制器中,我正在尝试做类似的事情......

 def show
    @group = Group.find(params[:id])
    @shots = Shot.where(GroupShot.where(:group_id => @group.id))

我收到错误“无法访问ActiveRecord :: Relation”。这样做的正确方法是什么?我正在使用Rails 3.2

修改

......我的模特......

#app/models/group_shot.rb
class GroupShot < ActiveRecord::Base
  belongs_to :shots
  belongs_to :groups
  attr_accessible :group_id, :shot_id

#app/models/group.rb
class Group < ActiveRecord::Base
  has_many :shots, through: :group_shot
  attr_accessible :name
end

#app/models/shot.rb
class Shot < ActiveRecord::Base
  has_many :groups, :through => :group_shot

2 个答案:

答案 0 :(得分:3)

假设您的群组模型设置如下:

class Group < ActiveRecord::Base
  has_many :group_shots
  has_many :shots, through: :group_shots
end

class Shot < ActiveRecord::Base
  has_many :group_shots
  has_many :groups, :through => :group_shots
end

class GroupShot < ActiveRecord::Base
  belongs_to :shot
  belongs_to :group
end

然后你可以做类似

的事情
@shots = @group.shots

答案 1 :(得分:1)

如果“关联通过”配置正确:

@group = Group.find(params[:id])
@shots = @group.shots