I want to show data from 4 models into a single view. I have created a separate controller for this named posts_controller.rb and in views I have created posts folder and created index.html.erb file.
After that in controllers file I have added the following code.
class PostsController < ApplicationController
def index
@quotes = Quote.all.order("created_at DESC")
@images = Image.all.order("created_at DESC")
@jokes = Joke.all.order("created_at DESC")
@items = (@quotes.to_a + @jokes.to_a)
end
end
And here is the view file where I am trying to show 2 items data as for now. But its not working. Pls check the code.
<% if @items.any? %>
<div class="col-md-12">
<% @items.each.do |item| %>
<% if item.is_a? Quote %>
<div class="postbg">
<%= quote.quotefie %>
<div class="wedate pull-right wehi">
<%= quote.created_at.strftime("%b %d, %Y") %>
</div>
<div class="clearfix"></div>
<em class="pull-right wehi" style="margin-top:20px;"> - <%= quote.author %></em>
<%= link_to 'Show', quote %>
<%= link_to 'Edit', edit_quote_path(quote) %>
<%= link_to 'Destroy', quote, method: :delete, data: { confirm: 'Are you sure?' } %>
</div>
<% else %>
<% @jokes.each do |joke| %>
<div class="postbg">
<%= joke.jokefie %>
<div class="wedate pull-right wehi">
<%= joke.created_at.strftime("%b %d, %Y") %>
</div>
<div class="clearfix"></div>
<%= link_to 'Show', joke %>
<%= link_to 'Edit', edit_joke_path(joke) %>
<%= link_to 'Destroy', joke, method: :delete, data: { confirm: 'Are you sure?' } %>
</div>
<% end %>
<% end %>
</div>
<% end %>
Here is the error it is showing.
undefined method `do' for #<Enumerator:0x007fd55fb032b8>
Your problem is in this line here:
<% @items.each.do |item| %>
do
defines a block, not a method call, so it should be:
<% @items.each do |item| %>
Note the removed .
.
You've used do
correctly further down the view when you use @jokes.each do |joke|
.
This line
<% @items.each.do |item| %>
should be
<% @items.each do |item| %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.