Rails - Create an helper method that print a specific attribute of all objects (render an array instead)
Sorry for this simple questio开发者_JAVA百科n but I am stuck here.
I am trying to create a helper method that simply prints for each object the attribute "name" of my Table "Term".
I tried this:
def display_name(terms)
terms.each do |term|
p term.name
end
end
But instead of printing each objects name, it prints an array for each object with all attributes.
As an example:
[#<Term id: 1, name: "test", definition: "first definition", created_at: "2011-07-21 14:52:12", updated_at: "2011-07-21 14:52:12">,
#<Term id: 2, name: "second test", definition: "blabla", created_at: "2011-07-20 18:00:42", updated_at: "2011-07-20 18:04:15">
I am trying to find what I can do with the documentation (content_tag, concat, collect) but it doesn't seem to provide the result I want..
Thanks for your explanation
The reason for this is because it does not actually print the name, it returns the value from terms.each since that was the last statement in the method.
I would probably use the map
method to collect all the names into an array first and if you want a String instead of an Array then I would join
them with whatever separator that is preferred, like this:
def display_name(terms)
terms.map(&:name).join ", "
end
You could also add a parameter to choose the separator if you like. Like this:
def display_name(terms, sep = ", ")
terms.map(&:name).join sep
end
# in view
display_name(collection, "<br/>")
By default it then uses a comma to separate them but you can manually choose something else.
精彩评论