问题
<% @labels.each do |label| %>
<input type="text" name="<%=label.name%>" value="<%=@car.(label.related_to) %>" class="big-font" style="width: <%=label.width%>px; top: <%=label.y_coor%>px; left: <%=label.x_coor%>px;" />
<% end %>
Hello guys, I'm new to rails so this should be a fairly easy question to answer.
The issue is here: <%=@car.(label.related_to) %>
.
label.related_to holds the string "make". I'm trying to get it to do this pretty much: @car.make
Any idea guys?
Thanks, Alain
回答1:
Use send
to send a message to an object:
@car.send(label.related_to)
If there is any chance of label.related_to
not being a valid method for the object, you'll probably want to be prepared to catch the NoMethodError
回答2:
You could use try
method.
<%= car.try(label.related_to) %>
try
would try to call the method on car
. However, if the method (ie. make
) does not exist it would throw an error.
You could make use of respond_to?
to ensure that the method exist:
<%= car.try(label.related_to) if car.respond_to?(label.related_to) %>
来源:https://stackoverflow.com/questions/4800836/call-a-method-on-a-variable-where-the-method-name-is-in-another-variable