Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 比较rails中同一类实例变量的两个元素_Ruby On Rails_Arrays_Compare - Fatal编程技术网

Ruby on rails 比较rails中同一类实例变量的两个元素

Ruby on rails 比较rails中同一类实例变量的两个元素,ruby-on-rails,arrays,compare,Ruby On Rails,Arrays,Compare,这将是非常基本的,但我是新手rails请帮助。 我在名为@product的类实例变量中得到了一些结果。我想比较两个产品的结果@产品有多个ID。我想比较连续的ID。下面是我要做的 <% @products.results.each do |result| bid=Brand.where("id=?",result.brand_id) bid1=Brand.where("id=?",result+1.brand_id) %> <% if (bid==bid

这将是非常基本的,但我是新手rails请帮助。 我在名为@product的类实例变量中得到了一些结果。我想比较两个产品的结果@产品有多个ID。我想比较连续的ID。下面是我要做的

<% @products.results.each do |result|
    bid=Brand.where("id=?",result.brand_id)
    bid1=Brand.where("id=?",result+1.brand_id)  %>
    <% if (bid==bid1) %>
       do something
    <% end %>
<% end %>

做点什么

但我没有得到结果。请告诉我哪里出了问题。

从您的代码来看,不清楚您想做什么,但有很多地方出了问题。逐一:

如果要在视图中完成所有这些操作,还需要在第2行和第3行中添加ERB标记
,否则它们将不会被解释为ruby代码,只会被打印为html

在您的视图中包含这么多逻辑通常不是一个好主意-如果需要,最好在模型甚至控制器中进行比较

result+1.brand\u id
将抛出错误,因为“1”没有方法“brand\u id”。大概您想要执行
result.brand\u id+1

代替
Brand.where(“id=?”,result.Brand\u id)
,您可以执行
Brand.find(result.Brand\u id)

您可以使用“include?”ruby方法

只需将所有ID存储在数组中,然后如示例所示执行以下操作:

a = [ 1, 2, 3 ]
a.include?(1)   #=> true
a.include?(4)   #=> false
有关更多详细信息,请访问以下链接:

试试这个

<% arr = @products.results.all %>
<% arr.shift %>
<% @products.results.each_with_index do |result,i| %>
    <% bid=result.brand %>
    <% if (bid==arr[i]) %>
       do something
    <% end %>
<% end %>

做点什么

首先将结果放入一个数组中,因此在控制器中可能类似于:

@results = @product.results
然后在视图中:

<% @results.each_with_index do |result, index|
  <% if result.brand_id == @results[index.next].brand_id %>
    # do something
  <% end %>
<% end %>

products.results有许多品牌标识,如1、23、23、20等。我想一次比较两个品牌标识。由于我使用的是products.results,如何比较这两个结果??您能否发布定义或进一步解释一下
产品
结果
品牌
模型之间的关系?@amesee products.results有许多品牌ID,如1、23、23、20等。我想一次比较两个品牌ID。由于我使用的是products.each,因此如何比较这两个结果??例如,在第一次迭代中,来自上述代码的bid=1。在同一次迭代中,我想将bid与bid1(存储下一个品牌id的变量。在本例中,bid1=23)进行比较。怎么做??