如何查找与其他表匹配id的表值 我有这张桌子:
Zombie_users Body_status
| id | name | | id| Zombie_id| body_id | status|
|----|------| --> |---|----------|---------|-------|
| 1 | Joe | | 1 | 1 | 2 | true |
Zobmie_users Tools Body_impacts
| id | name | | id |user_id| name | | id| tool_id| body_id | impact |
|----|------|--> |----|-------|------|--> |---|--------|---------|--------|
| 1 | Joe | | 1 | 1 |hammer| | 1 | 1 | 2 | 10% |
我需要找到user -> tools
的所有user --> Body_status = false
我的意思是,如果我们Body_impact -> body_id -> 2
和Body_status -> body_id -> 2
也有status = true
从列表中排除该工具
同样的事情:
@Body_status = @zombie.Body_status.where( Body_status: { :status=> false } )
@tools = @zombie.tools.includes(:Body_impacts).where( @Body_status.body_id } )
我知道这不是代码,但它完美地解释了所需操作的逻辑。
更新
我的模特:
class ZombieUser < ActiveRecord::Base
has_many :body_statuses
has_many :bodies, through: :body_statuses
has_many :tools
class BodyStatus < ActiveRecord::Base
belongs_to :zombie_users
belongs_to :bodies
class Tool < ActiveRecord::Base
belongs_to :zombie_users
has_many :body_impacts
has_many :bodies, :through => :body_impacts
accepts_nested_attributes_for :body_impacts,
class BodysImpact < ActiveRecord::Base
belongs_to :tools
belongs_to :bodies
答案 0 :(得分:0)
您可以使用ActiveRecord association extensions清除其中一些来电:
#app/models/zombie.rb
class Zombie < ActiveRecord::Base
has_many :body_statuses do
def false
where status: false
end
end
end
这将允许您致电:
@zombie = Zombie.find 1
@statuses = @zombie.body_statuses.false
我的意思是,如果我们
Body_impact -> body_id -> 2
和Body_status -> body_id -> 2
也有status = true
从列表中排除该工具
我认为您可以构建这样的查询:
@zombie = Zombie.find 1
@statuses = @zombie.body_statuses.false.pluck(:body_id) #-> array of IDs with "false" status
@user.tools.joins(:body_impacts).where('body_impacts.body_id IN (?)', @statuses)
## or
@user.tools.joins(:body_impacts).find_by(id: @statuses)