如果item_id有params - rails

时间:2013-12-19 06:07:31

标签: ruby-on-rails ruby-on-rails-3.2

尝试检查两个参数是否在我的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

3 个答案:

答案 0 :(得分:2)

可能你应该在模型中移动这个检查

if self.where(item_id: [params[:one] && params[:two]]).present? 

   then do this

else 

   do this

end

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

答案 1 :(得分:1)

我不确定我是否明白这一点,但试试这个:

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

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

答案 2 :(得分:0)

除了我已经提出的两个答案之外,你可能想要考虑一下:

您使用where函数来创建逻辑,但您需要考虑如何调用它。我就是这样做的:


自定义验证器

可能有点啰嗦,但您可以创建一个custom validator,您可以调用它来确定db中是否存在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的代码作为逻辑&amp; Rails guide for the custom validator

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