cannot display the view from the url parameter in ruby - ruby-on-rails

I was trying to display a list of the blog with the same category which display on the url parameter. however when i click the link it still stay at the same page.
route
match '/microposts/:category', :to => 'microposts#category_list'
view
<h2>sidebar</h2>
<% #categories= Micropost.select("category").group("category")%>
<% unless #categories.nil? %>
<ul><% #categories.each do |category| %>
<li><%= link_to category.category, :controller =>"microposts", :category => category.category, :method => 'category_list' %></li>
<% end %>
</ul>
<% end %>
After click the link enter category_list view.
category_list.html.erb
<h2>Catergory</h2>
<% #microposts.each do |post|%>
<article>
<h4><%= link_to post.title, post %>| <%= post.created_at %></h4>
</article>
<% end %>
<%= will_paginate #microposts %>
microposts controller
def category_list
#micropost = Micropost.select("category").where(params[:category])
#title = "Category"
end

Ok, try this:
UPDATED:
microposts_controller.rb
def category_list
#microposts = Micropost.where('category = ?', params[:category])
#categories = Micropost.select('DISTINCT(category)').map(&:category).compact
...
end
routes.rb
match '/microposts/:category' => 'microposts#category_list', :as => :microposts_category_list
_sidebar.html.erb
<h2>sidebar</h2>
<% unless #categories.empty? %>
<ul>
<% #categories.each do |category| %>
<li><%= link_to category, microposts_category_list_path(category) %></li>
<% end %>
</ul>
<% end %>

Related

Linking to basket/cart in ruby on rails

I have a menu in my header that has a show basket and a login button, each work when the code is placed in separately but not when both lines are in the file.
I'm using devise for the users.
Is there a better way to link to the current basket?
<li><%= link_to basket_path(#basket.id) do %>
<%= image_tag "/assets/viewBasket.png" %>
</li>
<% end %>
<% if signed_in? %>
<li><%= link_to edit_user_registration_path do%>
<%= image_tag"/assets/my_account.png" %></a></li>
<% end %>
<li><%= link_to destroy_user_session_path do%>
<%= image_tag"/assets/logout.png" %></li>
<%end%>
<% else %>
<li><%= link_to new_user_session_path do%>
<%= image_tag"/assets/loginRegisterBtn.png" %></li>
<% end%>
<% end %>
If I run on its own this works but not with the code after.
<li><%= link_to basket_path(#basket.id) do %>
<%= image_tag "/assets/viewBasket.png" %></li>
<% end %>
I think its to do with the way the current basket is set with the session id in the current_basket model.
module CurrentBasket
private
def set_basket
#basket = Basket.find(session[:basket_id])
rescue ActiveRecord::RecordNotFound
#basket = Basket.create
session[:basket_id] = #basket.id
end
end
The closing of <li> must be after the end of the link, like this:
<li>
<%= link_to basket_path(#basket.id) do %>
<%= image_tag "/assets/viewBasket.png" %>
<% end %>
</li>
I used the answer above which helped with one issue, however, I found that I had defined only the shop and index page. Removing this and it now works.
include CurrentBasket
before_action :set_basket, only: [:index, :shop]

Rails 4 params not being sent to the controller

I have been battling with what is going to turn out to be a quick answer for someone...
I have view with nested partials. The index has a partial to the categories which has a partial to the subcategories.
The categories are looping as expected but for some reason the locals don't seem to be reaching the controller.
My code is as follows:
index.html.erb
<%= render partial: "categories/categories", object: #categories %>
_categories.html.erb
<% #categories.each do |category| %>
<% if category.category_parent == 0 %>
<li><%= category.category_name %> <i class="icons icon-right-dir"></i>
<%= render partial: "categories/subcategories", object: #subcategories, locals: {parent_id: category.category_id} %>
</li>
<% end %>
<% end %>
_subcategories.html.erb
<% if #parent != nil %>
<ul class="sidebar-dropdown">
<li>
<ul>
<% #subcategories.each do |subcategory| %>
<li><%= subcategory.category_name %> <i class="icons icon-right-dir"></i></li>
<% end %>
</ul>
</li>
</ul>
<% end %>
categories_controller.rb
class CategoriesController < ApplicationController
before_action :categories, :subcategories
def categories
#categories = Category.all
end
def subcategories
#parent = params[:parent_id]
#subcategories = Category.where(:category_parent => params[:parent_id])
end
end
#categories is an instance variables, and you shouldn't need to pass it from view to view. So the first render statment becomes:
<%= render "categories/categories" %>
(I'm more familiar leaving off partial:)
_categories.html.erb becomes this:
<% #categories.each do |category| %>
<% if category.category_parent == 0 %>
<li><%= category.category_name %> <i class="icons icon-right-dir"></i>
<%= render "categories/subcategories", category: category %>
<%# Note passing in category to have access to it as a local %>
</li>
<% end %>
<% end %>
_subcategories.html.erb
<% if category != nil %>
<ul class="sidebar-dropdown">
<li>
<ul>
<% category.subcategories.each do |subcategory| %>
<li><%= subcategory.category_name %> <i class="icons icon-right-dir"></i></li>
<% end %>
</ul>
</li>
</ul>
<% end %>
I don't think you should be looking up #subcategories in your controller. It looks like in def categories you're just getting all the categories and then looping through them in the view. As it is, this will be n+1, as every time it loops over a new category, it will have to do a db query to find its subcategories. You can avoid this with includes.
categories_contorller.rb
def categories
#categories = Category.all.includes(:subcategories)
end
This is what I think is simplest and clearest. But I also haven't played with object: too much. This post might help you if you want to stick to that pattern:

how to get paginate to work instead of getting redirected to 'public/index.html'?

I have my homepage using 'public/index.html' which overrides everything from what I've read here.
As a result, I have all signed-in users to be redirected to http://localhost:3000/home which I have defined as get '/home' => 'static_pages#home', :as => :home in my routes
The problem I'm facing is that on the main page of signed-in users (/home), there's pagination.
When I try to click on page 2 http://localhost:3000/?page=2, it gets sent to public/index.html.
I tried the link http://localhost:3000/home/?page=2 as a test but it gives me a blank pagination. None of the items are displayed. How can I fix this?
Here's the controller
class StaticPagesController < ApplicationController
def home
if signed_in?
#post = current_user.microposts.build
#activities = PublicActivity::Activity.order("created_at desc").paginate(page: params[:page])
#feed_items = current_user.feed.paginate(page: params[:page])
#items = #activities + #feed_items
#items.sort_by{|item| item.class == PublicActivity::Activity ? item.created_at : item.created_at}
#items = #items.paginate(:page => 1, :per_page => 10)
else
redirect_to root_path
end
end
Then in my view
<%= render partial: 'shared/item', collection: #items %>
<%= will_paginate #items %>
Here's the _item.html.erb partial
<li id="<%= item.id %>">
<% if item.class == PublicActivity::Activity %>
<% if item.trackable_type == "Micropost" %>
<%= link_to item.owner.name, item.owner if item.owner %><span class="textname"> posted</span>
<% else %>
<%= link_to item.owner.name, item.owner if item.owner %><span class="textname"> made a comment </span>
<% end %>
<% else %>
<br>
<div class ="gravatarhome"><%= link_to gravatar_for(item.user), item.user %></div>
<%= link_to item.user.name, item.user %>
<span class="textname">shared this
<div class="FeedContent"><%= truncate(item.content, :length=>150, :omission=>' ...(continued)') %>
<% end %>
</li>

what should be the way to pass multiple activerecord object from controller to views?

I will give an example.
Say I have Category and Product as my two models and another ChosenProduct that specifies/handles the many to many relationship between them. Now when I have certain categories and I am iterating in a loop on these categories getting the corresponding products. How to access these multiple product objects in my view?
I am new to Rails and MVC so for now I am doing this task in my view itself. But I think this shouldn't be the right way. How should I approach this ?
I am adding my view code as asked. This works for me fine now. But I don't think its pretty.
<ul>
<% #categories.each do |category| %>
<li>
<%= image_submit_tag("add.png", :height => "20", :width => '20', :name=>"add_product_to_#{category.id}", :id=>"add_product_to_#{category.id}" ) %>
<%= category.category_name %>
<% #chosen_products = category.chosen_products %>
<% #chosen_products.each do |chosen_product| %>
<% #products = Product.where(:id => chosen_product.product_id).all %>
<% #products.each do |product| %>
<ul>
<li><%= product.product_name %>
<ul>
<li><%= image_tag("#{product.product_image_url}", :size => "200x200", :alt => "Can not load image!") %></li>
<li><%= product.product_image_url %></li>
</ul>
</li>
</ul>
<% end %>
<% end %>
<% end %>
</li>
</ul>
To iterate over a collection of objects of the same class, you must use a partial, it will iterate over your collection for you. Suppose this:
#controller
def index
#categories = Category.all
end
Then you will need a partial view called _category.html.erb in your views/categories/ with the logic of your view. Lets suppose your partial is:
<div class="info">
<p class="name"><%= category.name %></p>
</div>
The partial will receive a collection of categories, and it will iterate over the collection automatically. So in the partial you must call the object in the singular form, in this case category to refer the actual object that is being rendered.
Then in your index.html.erb view, all you need is to render the partial.
<%= render #categories %>
or
<%= render(partial: "categories/category", collection: #categories) || "<h1>There are no categories</h1>".html_safe %>
The second option will render what is next to || in case the collection #categories is empty.
I assume you have defined the associations between models as
app/models/chosen_product.rb
class ChosenProduct < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
app/models/category.rb
class Category < ActiveRecord::Base
has_many :chosen_products
has_many :products, through: :chosen_products
end
So in your your view you could do
<ul>
<% #categories.each do |category| %>
<li>
<%= image_submit_tag("add.png", :height => "20", :width => '20', :name=>"add_product_to_#{category.id}", :id=>"add_product_to_#{category.id}" ) %>
<%= category.category_name %>
<% category.products.each do |product| %>
<ul>
<li><%= product.product_name %>
<ul>
<li><%= image_tag("#{product.product_image_url}", :size => "200x200", :alt => "Can not load image!") %></li>
<li><%= product.product_image_url %></li>
</ul>
</li>
</ul>
<% end %>
</li>
<% end %>

Path helpers in a loop

I have a Foo that :has_many Bars. GET Foo#index shows all of the Bars. View looks like this:
<% #foos.each do |foo| %>
<% foo.bars.each do |bar| %>
<%= link_to 'Download', download_bar_path %>
<%= link_to 'New', new_bar_path( :foo => foo.id ) %>
<% end %>
<% end %>
There is a def download in Bars controller and a route:
resources :bars do
member do
get 'download'
end
end
rake routes shows
download_bar GET /bars/:id/download(.:format) {:action=>"download", :controller=>"bars"}
and URL /bars/1/download really works, but the first link in the view (download_bar_path) doesn't. It says No route matches {:action=>"download", :controller=>"bars"}.
What can be the problem?
<% #foos.each do |foo| %>
<% foo.bars.each do |bar| %>
<%= link_to 'Download', [:download, bar] %>
<%= link_to 'New', [:new, :bar] %>
<% end %>
<% end %>
You didn't specified the bar to download, you need to add it by changing this line
<%= link_to 'Download', download_bar_path(bar) %>

Resources