我正在尝试在表policy_logs中搜索它是否有pdf。
这是我的表格:
|policies|
|id| |name|
1 abc
2 def
3 ghi
|policy_logs|
|id| |name| |policy_id|
1 ab.pdf 1
2 cd.pdf 1
3 ef.pdf 3
4 ij.pdf 3
我正在尝试使用policy_logs中的所有列policy_id,例如“id”IN策略表
这是我的控制器:
@pdf = PolicyLog.find(:all,:select=>['policy_id as pdf'],:group=>['policy_id'])
@policy = Policy.find(:all,:conditions=>['id IN (?)',@pdf ])
这是我的模特:
class Policy < ActiveRecord::Base
has_many :policy_logs
end
class PolicyLog < ActiveRecord::Base
belongs_to :policy
end
我的观点在这里:
<% @policy.each do |p| %>
<%= p.id %>
<%= p.name %>
<% end %>
这是我想要的结果
|id| |policy_id|
1 1
3 3
我尝试了这个但是获得了NULL值:
@pdf = PolicyLog.find(:all,:select=>['policy_id as pdf'],:group=>['policy_id'])
@policy = Policy.find(:all,:conditions=>['id IN (?)',@pdf ])
这是日志:
SELECT policy_id as pdf FROM `policy_logs` GROUP BY policy_id
SELECT * FROM `policies` WHERE (id IN (NULL),(NULL),(NULL),(NULL))
还尝试使用数组0:
@pdf = PolicyLog.find(:all,:select=>['policy_id as pdf'],:group=>['policy_id'])
@policy = Policy.find(:all,:conditions=>['id IN (?)',@pdf[0].pdf ])
但我只得到一个结果,这是日志:
SELECT policy_id as pdf FROM `policy_logs` GROUP BY policy_id
SELECT * FROM `policies` WHERE (id IN (1))
还尝试使用数组1:
@pdf = PolicyLog.find(:all,:select=>['policy_id as pdf'],:group=>['policy_id'])
@policy = Policy.find(:all,:conditions=>['id IN (?)',@pdf[1].pdf ])
但我只得到一个结果,这是日志:
SELECT policy_id as pdf FROM `policy_logs` GROUP BY policy_id
SELECT * FROM `policies` WHERE (id IN (3))
最后我尝试了
@pdf= PolicyLog.find(:all,:select=>['policy_id as pdf'],:group=>['policy_id'])
@search= Policy.find(:all,:conditions=>['id IN (?)',@pdf.each do |a| { a.pdf} ])
但我得到了
odd number list for Hash.
unexpected ']', expecting kEND
也许还有其他方法可以搜索它。
请有人可以帮助我吗?
答案 0 :(得分:2)
试试这样:
@search = Policy.find(:all,:conditions => {:id => @pdf.map{|p| p.pdf})
或者:
@search = Policy.find(:all,:conditions => {:id => @pdf})