I am newbie to rails what I am trying was in my controller I have two methods
there are
def index
@books = Book.all
end
And My index.html looks like
s.no Name author
1 rails raj
2 electronics ravi
And I would Like to change the view of my Index.html.erb as shown in the bottom
and in
def show
@book = Book.find(params[:id])
book_rating = BookRating.where(:book_id =>@book.id)
rating_size = book_rating.size
@avg_satisfaction = book_rating.collect(&:satisfaction).sum.to_f/rating_size
@count= book_rating.count
end
What I wanted to do is display the count and avg_satisfaction according to books on index page as follows
s.no Name author satisfaction count
1 rails raj 45 1
2 electronics ravi 50 2
Please tell me how to do this, as I am unable to understand it. I am able to display in my show.html.erb but I want to display in my index.html.erb.
Please help me solve it.
My model for Books
class Book < ActiveRecord::Base
has_many :ratings, :through=> :users
has_many :book_profiles
has_many :profiles, :through => :book_profiles
accepts_nested_attributes_for :book_profiles, :allow_destroy => true
has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
end
mY BOOK RATINGS CONTROLLER
class BookRating < ActiveRecord::Base
belongs_to :user
belongs_to :Book
end
index.html.erb
<h1>Books List</h1>
<table id="book" border="3" layout= "fixed" width=" 100%" >
<colgroup>
<col style="width: 33%" />
<col style="width: 33%" />
<col style="width: 33%" />
<tr>
<th>#</th>
<th>Name</th>
<th>Logo</th>
<th>Place</th>
<th> RATING</th>
<th> Rank</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @books.each do |book| %>
<tr >
<td><%= book.id%></td>
<td><%= book.name %></td>
<td><%=image_tag book.logo.url(:thumb)%></td>
<td><%= book.place %></td>
<td><%= book.satisfaction %></td>
<td><%= book.rating %></td>
<% if !current_user.blank? %>
<td><%= link_to 'VIEW', book %></td>
<%else%>
<td><%= link_to 'VIEW', new_user_session_path,:class=>"login" %></td>
<%end %>
</tr>
<% end %>
</colgroup>
</table>
<br />
<%= link_to 'ADD New book', new_book_path %>
Book. all. Should beBook.all.@books = Book.all, now you just need to add to yourviews/books/index.htm.erbto display that info. What does your current index.htm.erb view look like?Book. allthat is preventing yourindex.html.erbfrom showing all the books? If you generated that code withrails generate....the table view should already be inindex.html.erb.ìndex.html.erbcontains right now? The code, not the rendered HTML.