I am trying to get this loop to iterate numbers at the end of cardtype. I can't figure out the right syntax. I have tried a bunch of different things.
See red arrow.
I am trying to get this loop to iterate numbers at the end of cardtype. I can't figure out the right syntax. I have tried a bunch of different things.
See red arrow.
If you really want to do it this way you could use the method send, in this way:
if @order.send("cardtype#{n}") != "none"
This will execute the method "cardtype#{n}" on the @order object.
However, this is generally not the best idea and I would suggest you look into turning this attribute in to a has_many relation or perhaps a serializable array.
Check out this tutorial on how associations work (it is most likely what you want to use): http://guides.rubyonrails.org/association_basics.html
As far as I understand, cardtypeN is a method (database column?) where N is an integer. It means there is no easy way to loop over these attributes as for the Ruby virtual machine itself these methods have no connections each other even if you call them cardtype1, cardtype2, etc.
And in fact, your code highlights a very poor design decision to me. If an order can have more card types, you should really h ave a cardtype model and associate order and cardtypes with a 1-to-many relationship.
However, to answer your question, you can dynamically compose the method using one of the following approaches:
# [] syntax
@order["cardtype#{n}"]
# send
@order.send("cardtype#{n}")
Each method has its own advantages and disadvantages. Said that, you can loop from 1 to the number of maximum cardtypes
<% 1.to(10).each do |index| %>
<% if @order["cardtype#{index}"] != "none" %>
whatever
<% end %>
<% end %>
However, as I mentioned, you really want to redesign your model.
[] notation does read a lot better. It's worth noting that your comments on the poor design decision stem from violating the Zero, One or Infinity Rule of software design. This seems to be a good candidate for a has_many relationship rather than a pile of columns.has_many, that's why I put some emphasis on it. I really feel that having method names with index values is a terrible approach.