Rails的-Y的方法来查询一个belongs_to的关联模型 [英] Rails-y way to query a model with a belongs_to association
问题描述
我有两个型号:
class Wine
belongs_to :region
end
class Region
has_many :wines
end
我试图用#where方法与将来自params哈希表的某些元素融入到一个查询的散列,例如 {建立了一个哈希:区域=> '2452'}
def index
...
@wines = Wine.where(hash)
...
end
不过,我得到的是一列不存在错误执行查询时:</ P>
But all I get is a column doesn't exist error when the query is executed:
ActiveRecord::StatementInvalid: PGError: ERROR: column wines.region does not exist
LINE 1: SELECT "wines".* FROM "wines" WHERE "wines"."region" =...
当然,表酒
的 REGION_ID
,所以如果我查询了 REGION_ID
,而不是我不会得到一个错误。
Of course, the table wines
has region_id
so if I queried for region_id
instead I would not get an error.
现在的问题是:
有一个导轨-Y方式查询酒
的特定对象区域
使用在
?我在下面列出一些选择依据是什么,我知道我能做到的。 #where
方法ID
Is there a rails-y way to query the Wine
object for specific regions
using the id
in the #where
method? I've listed some options below based on what I know I can do.
选项1:
我可以改变我构建查询哈希的方式,让每场都有 _id
(如 {:REGION_ID =&GT;'1234',:varietal_id =&GT;'1515'}
,但并不是所有的协会从酒
是 belongs_to的
因而不具备葡萄酒一个条目 _id
,使得逻辑更加复杂与联接,什么不是。
Option 1:
I could change the way that I build the query hash so that each field has _id
(like { :region_id => '1234', :varietal_id => '1515' }
but not all of the associations from Wine
are belongs_to
and thus don't have an entry in wines for _id
, making the logic more complicated with joins and what not.
选项2: 建立一个SQL where子句使用一些逻辑,再次确定是否使用id或加入反对另一个表...再次逻辑会稍微复杂一些,并且在钻研到SQL使得它觉得少轨-Y。或者,我可能是错在这一方面。
Option 2: Build a SQL where clause, again using some logic to determine whether to use the id or join against another table... again the logic would be somewhat more complicated, and delving in to SQL makes it feel less rails-y. Or I could be wrong on that front.
选项(S)3..n: 事情我还没想过......您输入放在这里:)
Option(s) 3..n: Things I haven't thought about... your input goes here :)
推荐答案
感谢所有谁回答。这些问题的答案我会是伟大的单一条件查询,但我需要的东西,可以处理不同数量的条件。
Thanks to all who replied. The answers I got would be great for single condition queries but I needed something that could deal with a varying number of conditions.
我最终实现我的选择#1,这是通过迭代和连接建立的条件散列 _id
来的值:
I ended up implementing my option #1, which was to build a condition hash by iterating through and concatenating _id
to the values:
def query_conditions_hash(conditions)
conditions.inject({}) do |hash, (k,v)|
k = (k.to_s + "_id").to_sym
hash[k] = v.to_i
hash
end
end
因此,该方法将采取一个从PARAMS建成这样的哈希
So that the method would take a hash that was built from params like this:
{ region => '1235', varietal => '1551', product_attribute => '9' }
和删除一个 _id
上的每个键结束和值更改为整数:
and drop an _id
onto the end of each key and change the value to an integer:
{ region_id => 1235, varietal_id => 1551, product_attribute_id => 9 }
我们将看到如何可持续发展是这样的,但是这是我和现在。
We'll see how sustainable this is, but this is what I went with for now.
这篇关于Rails的-Y的方法来查询一个belongs_to的关联模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!