如果item_id有参数 - 轨道



试图在我的rails应用程序中检查if语句的id字段中是否有两个参数。

例如,我想说明如果两个 [params[:one], params[:two]] 都存在于 :item_id 列中,然后继续,如果没有,请不要包含在结果中。

因此,在下面的示例中,它只会选择item_id一个,因为item_id中都存在一个和两个参数。

桌子

item_id | one  | two
   1    | 2300 | 2255
   1    | 2000 | 2304
   2    | 2300 | 2000
   3    | 2255 | 2222

查看表单代码

<%= form_tag vpc_search_path do %>
 <%= select_tag :one, options_from_collection_for_select(@variety, "variety_id", "variety_name", :selected => "2300"), include_blank: false %>
 <%= select_tag :two, options_from_collection_for_select(@variety, "variety_id", "variety_name", :selected => "2255"), include_blank: false %>
 <%= submit_tag "Compare" %>
<% end %>

控制器代码

if Result.where(trial_id: [params[:one], params[:two]])
   @comparison = Result.where('variety_id' => [params[:one], params[:two]], 'year' => params[:year])
else
   redirect_to vpc_index_url, notice: "error."
end

也许你应该移动这个检查模型

if self.where(item_id: [params[:one] && params[:two]]).present? 
   then do this
else 
   do this
end

或者可能如果你能提供参数哈希结构,我可以改进我的答案

我不确定我是否理解正确,但请尝试以下操作:

if SomeModel.where(item_id: [params[:one],params[:two]]).count == 2
  #params :one and :two are on the item_id column
else
  #one or both are not on the item_id column
end

请更好地解释您的问题,很难理解

除了我已经投了赞成票的两个答案之外,你可能要考虑一下:

您将使用 where 函数来创建逻辑,但您需要考虑如何调用它。以下是我会怎么做:


自定义验证器

可能有点冗长,但您可以创建一个自定义验证器,您可以调用它来确定数据库中是否存在params

class TableValidator < ActiveModel::Validator
  def validate(record)
    unless self.where(item_id: [record.one && record.two]).present? 
      record.errors[:name] << 'Need a name starting with X please!'
    end
  end
end
class Table
  include ActiveModel::Validations
  validates_with TableValidator
end

我使用了Magnum的代码作为逻辑,并使用了自定义验证器的Rails指南

这可能不会开箱即用,但这就是我会看的

最新更新