How can I display a list of three different Models sortable by the same :attribute in rails?
I have a Campaign model which has_many Calls, Emails, and Letters.
For now, these are each a separate Model with different controllers and actions (although I would like to start to think of ways to collapse them once the models and actions stabilize).
They do share two attributes at least: :days and :title
I would like a way to represent all the Calls, Emails, and Letters that belong_to a specific Campaign as a sortable collection (sortable by :days), in a way that outputs the model name and the path_to() for each.
For example (I know the below is not correct, but it represents the kind of output/format I've been trying to do:
@campaign_events.each do |campaign_event|
<%= campaign_event.model_name %>
<%= link_to campaign_event.title, #{model_name}_path(campaign_event) %>
end
Thanks so much. BTW, if this matters, I would then want to make the :days attribute 开发者_开发技巧editable_in_place.
Here is what I've got working, but want some additional insights
module CampaignsHelper
def campaign_events
return (@campaign.calls + @campaign.emails + @campaign.letters).sort{|a,b| a.days <=> b.days}
end
end
In the VIEW:
<% @campaign_events = campaign_events %>
<% @campaign_events.each do |campaign_event| %>
<% model_name = campaign_event.class.name.tableize.singularize %>
<p>
<%= link_to campaign_event.title, send("#{model_name}_path", campaign_event) %>
<%= campaign_event.days %>
</p>
<% end %>
Like this?
# controller
@campaign = Campaign.find(params[:id])
@campaign_events = (@campaign.calls + @campaign.emails + @campaign.letters).sort{|a,b| a.days <=> b.days}
# view
@campaign_events.each do |campaign_event|
<%= campaign_event.model_name %>
<%= link_to campaign_event.title, #{model_name}_path(campaign_event) %>
end
In controller you find all campaign events and sort it by days
field
精彩评论