Reputation: 15384
I cant figure out what parameters to select for comparison for the following scenario.
I want to link to a specific page on my site depending upon which scope is being used to grab the data being presented on my home page..Is this possible?
For example I have a posts and departments model, relationships as so
Post
belongs_to :department
Department
belongs_to :post
I grab the posts via a scope and then have a method to grab the first post from its scope.
scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"
scope :woodside_posts, :include => :department, :conditions => {"departments.name" => "Woodside"}, :order => "posts.published_on DESC"
Then to show the first post from each
def self.top_posts
#Array with each of the 4 departments - first record
top_posts = [
self.tynewydd_posts.first,
self.woodside_posts.first,
self.sandpiper_posts.first,
self.outreach_posts.first
]
#remove entry if nil
top_posts.delete_if {|x| x==nil}
return top_posts
end
In my view then i iterate through the top posts
<% @toppost.each do |t| %>
<%= link_to 'Read more' %> <!-- Want to put a helper method here -->
<% end %>
Routes
/tynewyddnews #tynewydd_posts
/woodsidenews #woodside_posts
Within the @toppost instance variable i have the attribute department.name available, i access via t.department.name in my .each loop.
How would i go about saying "if @toppost.department.name == "xxxx" then link_to "/path" for example. just looking for some tips on structure or if this can be converted into a case statement then that would be even better
Thanks
Upvotes: 0
Views: 112
Reputation: 6088
You could use a hash instead of a array, and then only return the key's since you won't be needing their values:
def self.top_posts
top_posts = { "tynewydd" => self.tynewydd_posts.first,
"woodside" => self.woodside_posts.first,
"sandpiper" => self.sandpiper_posts.first,
"outreach" => self.outreach_posts.first
}
top_posts.delete_if {|x| x.value==nil}
return top_posts.keys
end
Now you are getting an array of the hash keys like this:
["tynewydd","woodside",..]
And in your view:
<% @toppost.each do |t| %>
<%= link_to 'Read more', "#{t}news_path" %>
<% end %>
Upvotes: 1