has_many通过关联和多个搜索条件,我该如何使这项工作?

时间:2011-09-21 16:37:24

标签: ruby-on-rails

我正在尝试创建一个多标准搜索表单。我想通过GET提交所有搜索部分,如果他们分配了值,我希望他们进行评估。我遇到麻烦的事情就是构建一个查询,当你通过关联进行查询时,我可以将更多查询分层。

只是为了让您了解我的模型是如何设置的:

class Client < ActiveRecord::Base
  has_many :campaigns
  has_many :pieces, :through => :campaigns
end

class Campaign < ActiveRecord::Base
  belongs_to :client
  has_many :pieces
end

class Piece < ActiveRecord::Base
  belongs_to :client
end

现在,考虑到这个模型,我正在使用collect方法来抓取具有共同组织的碎片。

if params.has_key?(:criteria)
    @selected_client = Client.where(:organization => "Org1")
    @pieces = @selected_client.collect{ |c| c.pieces }.flatten
end

是否有某种格式化查询字符串的方法,以便我可以缩小@pieces,再多几次?假设我想通过关联再次使用它,以获得具有另一个相同客户标准的碎片......

非常感谢!我的大脑在这一点上是一个椒盐脆饼。

2 个答案:

答案 0 :(得分:1)

我不确定我是否能够很好地理解你要做的事情。如果您想获得符合客户标准的所有部分,请在rails 3中执行此操作:

@pieces = Piece.joins(:campaign => :client).where(:clients => {:organization => criteria})

从组织“Org1”获取属于客户的所有部分。

正如@Andrew所说,您可以根据需要添加任意数量的where语句来添加新条件。的 See this for more information

答案 1 :(得分:0)

你的第一段被切断,仅供参考。

如果@pieces是一个数组,您可以使用find块来进一步缩小搜索范围。虽然这会将负载放在服务器CPU而不是SQL数据库上。

您可以堆叠where语句,Rails会自动为您创建一个查询。以下是我们网站的应用商店部分的一些示例代码:

@platform = params[:platform]
@category = params[:category]
@search   = params[:app_q]

# Get initial SQL, narrow the search, and finally paginate
@apps = App.live

@apps = @apps.where("platform = ?", AppPlatforms.value(@platform)) if AppPlatforms.value(@platform)
@apps = @apps.where("(name LIKE ? OR description LIKE ?)", "%#{@search}%", "%#{@search}%") if @search
@apps = @apps.where("id IN(?)", @cat.apps) if @category && @cat = Category.find_by_id(@category)

@apps = @apps.paginate(:page => params[:page], :per_page => 10, :order => "name")

您应该能够使用collect来缩小搜索范围,而不是使用@selected_client.pieces.where(...)

我希望这是朝着正确方向发展的一点!