How to find table values with matching id with other table.
I have this 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% |
I need to find all the user -> tools
that have user --> Body_status = 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
samething like that:
@Body_status = @zombie.Body_status.where( Body_status: { :status=> false } )
@tools = @zombie.tools.includes(:Body_impacts).where( @Body_status.body_id } )
I know that's not working code, but it perfectly explains the logic of the desired action.
update
My models:
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
You could clean up some of those calls with ActiveRecord association extensions :
#app/models/zombie.rb
class Zombie < ActiveRecord::Base
has_many :body_statuses do
def false
where status: false
end
end
end
This will allow you to call:
@zombie = Zombie.find 1
@statuses = @zombie.body_statuses.false
I mean if we have
Body_impact -> body_id -> 2
andBody_status -> body_id -> 2
that also havestatus = true
exclude that tool from the list
I think you could build a query like this:
@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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.