<h1>Scope1</h1>
<% Model.scope1.each do |record| %>
<%= record.attribute%>
<% end %>
<h1>Scope2</h1>
<% Model.scope2.each do |record| %>
<%= record.attribute%>
<% end %>
%w(scope1 scope2).each do |scope|
<h1><%= scope %></h1>
<% Model.scope.each do |record| %>
<%= record.attribute%>
<% end%>
<% end %>You can use send method for calling scopes as followed:
<%- %w(scope1 scope2).each do |scope|
<h1><%= scope %></h1>
<%- Model.send(scope.to_sym).each do |record| %>
<%= record.attribute%>
<%- end%>
<%- end %>
Thanks,You can use send method for calling scopes as followed:
<%- %w(scope1 scope2).each do |scope|
<h1><%= scope %></h1>
<%- Model.send(scope.to_sym).each do |record| %>
<%= record.attribute%>
<%- end%>
<%- end %>
However looping more than a scope may cause huge data to be rendered on a single page. I would suggest avoiding this.
Following is an way to you can avoid looping multiple scopes on a single page:
1. Keeping a select list on the page may help you to display only selective data. For example say you are having model User as :
class User < ActiveRecord::Base
scope :active, -> { where active: true }
scope :inactive, -> { where active: false }
end
Then your select list will be :
<%= select_tag(:scope_name, options_for_select([['All', 'all'], ['Active Users', 'active'], ['InActive Users', 'inactive'],...])) %>
With JS/JQuery you can write coding to send a get request to the
controller which you were using for displaying data. So when user will
be selecting any option the page will get reloaded. It can be done using
following code:
$(function(){
$('#scope_name').change(function(){
window.location.replace('/users?scope_name='+ $(this).val());
})
}
With above coding you will be getting scope_name parameter in params in your controller.
Use this params to retrieve records in controller only as follows:
In my controller action:
def index
@scope_name = if %w(all, active, inactive).includes?(params[:scope_name]) # taking care that proper scope name is passed here
params[:scope_name]
else
'all'
end
@records = User.send(@scope_name.to_sym)
end
end
<h1><%= @scope_name.titleize %></h1>
<%- @records.each do |record| %>
<%= record.first_name%>
<%- end%>
This way you will be having selective data on a page and you will not have to fire any query from view.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/8e9a2094-60a6-46f1-a4f0-a1fb8fffda90%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.