【问题标题】:Rails, find table where match another tableRails,查找与另一个表匹配的表
【发布时间】:2016-01-09 13:32:37
【问题描述】:

如何查找 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 --> 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

【问题讨论】:

  • 你能在问题中发布你的模型吗?
  • 请把你的协会放在这里。
  • @Pavan ,谢谢,我添加了模型。

标签: ruby-on-rails associations rails-activerecord has-many-through has-and-belongs-to-many


【解决方案1】:

您可以使用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 -&gt; body_id -&gt; 2Body_status -&gt; body_id -&gt; 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)

【讨论】:

  • 感谢完美!只有第二个选项没有按预期工作。我只能通过这种方式让它工作:@user.tools.joins(:body_impacts).find_by(body_impacts: { body_id: @statuses})
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 2011-08-15
  • 2013-01-20
  • 1970-01-01
  • 2021-12-04
相关资源
最近更新 更多