0

So I'm trying to set a conditional statement for what images should be displayed

This is the section in my home/index view file

<% if @cloth.gender == "Female" && @cloth.size == "2T-3T" || "4T-5T" %>

This returns an error in the browser:

undefined method `gender' for #<Array:0x4d2c578>

I set the home controller to:

def index
  @cloth = Cloth.all
end

So it should be able to access all of "cloth", but it isn't. When I go into the rails console I can access cloth.gender. Not sure what to do here...

Entire code available at https://github.com/yahtaa/oslr

4

3 回答 3

4

更好的方法是使用each@cloths 上的方法:

<% @cloths.each do |cloth| %<
  <% if cloth.gender == "Female" && cloth.size == "2T-3T" || "4T-5T" %>
....

注意我说@cloths ...您可能应该将您的索引def更改为@cloths = Cloth.all(只是让您的代码更清晰一些)。

编辑

如评论和codeit的答案中所示,您最初编写的条件存在问题。另一种写法是

<% if cloth.gender == "Female" && (cloth.size == "2T-3T" || cloth.size == "4T-5T") %>

感谢 codeit 发现了这个问题。

于 2013-04-11T14:01:29.610 回答
3

尝试这个:

 @cloths.each do |cloth|
   if cloth.gender == "Female" && ["2T-3T", "4T-5T"].include?(cloth.size)
      #Or use  `if cloth.gender == "Female" && (cloth.size == "2T-3T" || cloth.szie == "4T-5T")`
   ..
 end

(cloth.size == "2T-3T" || "4T-5T")cloth.size当value 为时将返回 false 4T-5T。因为"2T-3T" || "4T-5T"总是2T-3T

于 2013-04-11T14:29:03.450 回答
3

Cloth.all will return an instance of an Array. You'll need to either use each to iterate over all the instances that Cloth.all returns, or grab an instance with @cloth[0], for example.

于 2013-04-11T13:59:44.747 回答