Rails,找到匹配另一个 table 的 table

Rails, find table where match another table

如何找到与其他 table.
匹配 ID 的 table 值 我有这个 tables:

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 --> Body_status = falseuser -> tools
我的意思是如果我们有 Body_impact -> body_id -> 2Body_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

您可以使用 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

I mean if we have Body_impact -> body_id -> 2 and Body_status -> body_id -> 2 that also have status = true exclude that tool from the list

我认为您可以像这样构建查询:

@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)