different controllers and methods - ruby-on-rails-3

I'm a beginner and there is something I'm a bit confused with.
I have a website that is similar to Metacritic for TV Shows, my two tables are shows and reviews.
There is my show (as in tv show) controller
def show
#show = Show.find(params[:id])
#reviews = #show.reviews.paginate(page: params[:page])
#ratings = #show.reviews.average("rating")
respond_to do |format|
format.html # show.html.erb
format.json { render json: #show }
end
end
and my show view
<p id="notice"><%= notice %></p>
<div class="row">
<aside class="span4">
<section>
<h1>
<p>
<%= #show.name %> ( <%= #show.year %>
)
</p>
<p>
<b>Synopsys:</b>
<%= #show.synopsys %>
</p>
<p>
<b>Note:</b>
<%= #ratings %>
</p>
<%= image_tag #show.avatar.url %>
</h1>
</section>
<section>
</section>
</aside>
<div class="span8">
<% if #show.reviews.any? %>
<h3>Reviews (<%= #show.reviews.count %>)</h3>
<ol class="reviews">
<% #reviews.each do |review| %>
<%= review.content %> <br> <%= review.source %> | <b><%= review.rating %> </b><br><br>
<br><br>
<% end %>
</ol>
<%= will_paginate #reviews %>
Now, I'm trying to do a similar thing on my home view (controller home). I want to add all the shows to the database and their overall ratings. The issue if that when I copy the content of my show controller to my home controller, review is undefined and I don't understand why.
Anyone can help ?
class HomeController < ApplicationController
def index
#shows = Show.all
#ratings = #show.reviews.average("rating")
respond_to do |format|
format.html # show.html.erb
format.json { render json: #show }
end
def about
end
def contact
end
end
end

Related

No route matches [POST] "/portfollios/new"

Hey Guys I am getting issue, No Route Matches, though I have created both new as well as create method.
portfollios_controller.rb
class PortfolliosController < ApplicationController
def index
#portfolio_items = Portfollio.all
end
def new
#portfolio_item = Portfollio.new
end
def create
#portfolio_item = Portfollio.new(params.require(:portfollio).permit(:title, :subtitle, :body))
respond_to do |format|
if #portfolio_item.save
format.html { redirect_to portfollio_path, notice: 'Your portfolio item is now live.' }
else
format.html { render :new }
end
end
end
end
routes.rb
Rails.application.routes.draw do
resources :portfollios
end
new.html.erb
<h1>Create a new Portfolio Item</h1>
<%= form_with(model: #portfolio_items, local: true) do |form| %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div class="field">
<%= form.label :subtitle %>
<%= form.text_field :subtitle %>
</div>
<div class="field">
<%= form.label :body %>
<%= form.text_area :body %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Can someone help me out with the issue. I am not able to figure it out.
I figured it out. The issue is with with the file new.html.erb
I needed to change below line:-
<%= form_with(model: #portfolio_items, local: true) do |form| %>
to
<%= form_with(model: #portfolio_item, local: true) do |form| %>
It should be #portfolio_item not plural.

Comments route in Rails 5.1

I am trying to create Comments on User created Articles in Rails 5.1.
After a Comment is submitted, the redirect should be to the '/articles/:id' but is instead redirecting to '/articles/:id/comments'.
I'm using nested routing in routes.rb:
devise_for :users
root to: "articles#index"
resources :articles do
resources :comments
end
My CommentsController.rb:
class CommentsController < ApplicationController
before_action :set_article
def create
unless current_user
flash[:alert] = "Please sign in or sign up first"
redirect_to new_user_session_path
else
#comment = #article.comments.build(comment_params)
#comment.user = current_user
if #comment.save
flash[:notice] = "Comment has been created"
else
flash.now[:alert] = "Comment not created correctly"
end
redirect_to article_path(#article)
end
end
private
def comment_params
params.require(:comment).permit(:body)
end
def set_article
#article = Article.find(params[:id])
end
end
The form for Comments in articles/show.html.erb:
<!--Start of comments-->
<div class="col-md-12">
<%= form_for [#article, #comment],
:html => {class: "form-horizontal", role: "form"} do
|f| %>
<% if #comment.errors.any? %>
<div class="panel panel-danger col-md-offset-1">
<div class="panel-heading">
<h2 class="panel-title">
<%= pluralize(#comment.error.count, "error") %>
prohibited this comment from being saved:
</h2>
<div class="panel-body">
<ul>
<% #comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
</div>
<% end %>
<div class="form-group">
<div class="control-label col-md-2">
<%= f.label :body, 'New Comment' %>
</div>
<div class="col-md-10">
<%= f.text_area :body, rows: 10, class: "form-control", placeholder: "New Comment" %>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<%= f.submit "Add Comment", class: "btn btn-primary btn-lg pull-right" %>
</div>
</div>
<% end %>
</div>
How do I make this submit button save and redirect back to 'articles/:id'? Thanks in Advance.
The routes generated by in your router will look something like this:
/articles/:article_id/comments/:id
This means, when you need to load your article in the CommentsController, you should do something like this (as suggested by #Marlin):
def set_article
#article = Article.find(params[:article_id])
end
Otherwise, you run the risk of attaching the comment to the incorrect article if there happens to be an ID collision between the IDs in the comments and article table. Or you simply get a ActiveRecord::RecordNotFound error.
But I know, that this doesn't answer your question directly, ut I suspect that the issue is that you're loading the wrong record from the db somewhere because of the above mentioned.
Try updating your code, and write a test, to make sure that you can programmatically reproduce the error :)

yield is not working in partials other than application.html.erb

Here I have a requirement to use yield in a partial other than application.html.erb , when I try this in partial it was showing me the blank value and if I try the yield in application.html.erb it was showing the value.
application.html.erb
body>
<div id="main-container">
<%= content_for?(:page_header) ? yield(:page_header) : (render :partial => "/shared/home_header") %>
<div id="middle-container">
<%= yield %>
</div>
<div id="bottom-container">
<%= render "/shared/bottom_partial" %>
</div>
index.html.erb
<% content_for :page_header do %>
<%= render :partial => "/shared/employer_header" %>
<% end %>
<% content_for :page_name do %>
<p>My Account</p>
<% end %>
<div>
xxxxxxxxxxxxxx
xxxxxxxxxxxxxx
</div>
/shared/_employer_header.html.erb
<div class="heading" >
<%= yield(:page_name) %>
</div>
When I am trying like above I am getting blank value in yield :page_name in employer header if I try the yield :page name in application.html.erb I am getting the value.Can any one help me to sort this out.Thank'U'.
Swap the order of your two content_fors so the :page_name is defined before the partial is rendered.
index.html.erb
<% content_for :page_name do %>
<p>My Account</p>
<% end %>
<% content_for :page_header do %>
<%= render :partial => "/shared/employer_header" %>
<% end %>

RoR: why aren't my microposts showing up?

Here is the users show view where they are supposed to show up. ..
edit (I have updated this post slightly you can see it at RoR: How can I get my microposts to show up?)
<section>
<div id= "purchases">
<%= render 'shared/micropost_form_purchase' %>
</div>
<div id="sales">
<%= render 'shared/micropost_form_sale' %>
</div>
</section>
<div id="purchases list">
<ol class="microposts">
<%= render #purchases unless #purchases.nil? %>
</ol>
</div>
<div id="sales list">
<ol class="microposts">
<%= render #sales unless #sales.nil? %>
</ol>
</div>
so the forms (partials) are loading fine, but then when I make a post, in either one, neither the purchases list nor the sales list shows up. I checked the database and they are being created along with an entry in the column indicating kind (either sale or purchase)
Here are the forms:
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "purchase" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
and
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
also, here is the show part of the users_controller.rb
def show
#user = User.find(params[:id])
#micropost=Micropost.new
#microposts = #user.microposts.paginate(page: params[:page])
end
and here is the show part of the microposts_controller.rb
def show
#micropost = Micropost.find(params[:id])
#microposts = Micropost.where(:user_id => #user.id)
#purchases = #microposts.where(:kind => "purchase")
#sales = #microposts.where(:kind => "sale")
end
can anyone help me out? anything else i need? hmmm
First, just to be sure you are getting the results you want, you should try something like this in your view
<%= #sales %>
This should be a hash of the results you want. Then, if that looks good, you want to do something like this
<div id="sales_list">
<ol class="microposts">
<% if #sales.any? %>
<% #sales.each do |sale| %>
<li><%= sale %></li>
<% end %>
<% end %>
</ol>
</div>
And repeat for purchases

Admin Products Routing

Hi hoping to get some answers here. I have thought this over and over, it is killing me. Want to get answers now, everything i have been finding is more complex then my litle system at the moment. Question is below information.
First my routes file:
get 'admin' => 'admin#index'
namespace "admin" do
resources :products
end
My Admin Products Controller is as follows:
class Admin::ProductsController < ApplicationController
# GET /products
# GET /products.json
def index
#products = Product.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #products }
end
end
# GET /products/1
# GET /products/1.json
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #product }
end
end
# GET /products/new
# GET /products/new.json
def new
#product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #product }
end
end
# GET /products/1/edit
def edit
#product = Product.find(params[:id])
end
# POST /products
# POST /products.json
def create
#product = Product.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render json: #product, status: :created, location: #product }
else
format.html { render action: "new" }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.json
def update
#product = Product.find(params[:id])
respond_to do |format|
if #product.update_attributes(params[:product])
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product = Product.find(params[:id])
#product.destroy
respond_to do |format|
format.html { redirect_to products_url }
format.json { head :ok }
end
end
end
My Admin Products View files are standard, here is the _form, new, index files:
New:
<%= render 'form' %>
<%= link_to 'Back', admin_products_path %>
_form:
<%= form_for [:admin, #product] do |f| %>
<% if #product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% #product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, rows: 6 %>
</div>
<div class="field">
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Index:
<h1>Admin Listing products</h1>
<table>
<% #products.each do |product| %>
<tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
<td>
<%= image_tag(product.image_url, class: 'list_image') %>
</td>
<td class="list_description">
<dl>
<dt><%= product.title %></dt>
<dd><%= truncate(strip_tags(product.description),
length: 80) %></dd>
</dl>
</td>
<td class="list_actions">
<%= link_to 'Edit', edit_admin_product_path(product) %><br/>
<%= link_to 'Destroy', admin_product_path(product),
confirm: 'Are you sure?',
method: :delete %>
</td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New product', new_admin_product_path %>
Ok I hope that is all the information that is needed to help me.
This is the question: if i go to localhost:3000/admin/products/new
I get to the form to create a new product. However if i complete the form it takes me to the following localhost:3000/product/:id. I want it to redirect_to admin/products.
I keep telling myself that it has to be the redirect_to in the "create" procedure on the admin products controller, but tried everything and it is not working..... Please help it is kill me lol
JUst redirect to your index action instead of showing the product. This also applies to your update action if at all you also want the user to be redirected to the index page if they update a product. Just change redirect_to #product to redirect_to :action => 'index'.
That did not work, however here is a step by step guide.
http://icebergist.com/posts/restful-admin-namespaced-controller-using-scaffolding