I'm trying to simplify and DRY up my rails code so as not to duplicate lists of URLs in multiple places and have to keep them in sync. I have a controller with a method parent that has instance variables for lists of urls in different categories, i.e.
def parent
@collection1 = [
["Link 1", "http://link1.com"],
["Link 2, "http://link2.com"]
]
@collection2 = [
["Link 3", "http://link3.com"],
["Link 4, "http://link4.com"]
]
end
Then in my views I have a file parent.html.erb with code
<% @collection1.each do |link| %>
<a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>
<% @collection2.each do |link| %>
<a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>
But I have another view, child.html.erb that I want to just display collection 1, so
<% @collection1.each do |link| %>
<a href="<%= link[1] %>" target = "_blank" class="btn btn-primary btn-block" role="button"><%= link[0] %></a>
But in order to do this I have to define another method in the same controller:
def child
@collection1 = [
["Link 1", "http://link1.com"],
["Link 2, "http://link2.com"]
]
which is the same collection as I have in the parent method. That works but then if I want to change one the links I have to change it in both places. Please advise, I am pretty new to rails but realize this can't possibly be the way you're supposed to this! Thank you.
Aucun commentaire:
Enregistrer un commentaire