Ok, so I know this isn't preferred method, but my client needs fixed urls that can be indexed by Google and dynamic urls won't cut it. Everything works great, all my product resources work as they should, except on the 4th and final nest, I can't get a list of my objects on the subcategories/show route; I am sure I am missing something simple.
routes
resources :locations do
resources :categories do
resources :subcategories do
resources :products
end
end
end
subcategories/show view
I need to list the products that belong to the subcategory
...
<h1><%= #subcategory.name %></h1>
<%= sanitize #subcategory.body %>
...
<% #location...#category...#subcategory.products.each do |p| %>
<tr>
<td><%= p.name %></td>
<td><%= p.slug %></td>
<td><%= link_to 'Show', location_category_subcategory_product_path(#location, #category, #subcategory, p) %></td>
</tr>
<% end %>
...
subcategory model
has_many :products
products model
belongs_to :subcategory
products_controller
def index
#location = Location.friendly.find(params[:location_id])
#category = Category.friendly.find(params[:category_id])
#subcategory = Subcategory.friendly.find(params[:subcategory_id])
#products = Product.all
end
def show
#location = Location.friendly.find(params[:location_id])
#category = Category.friendly.find(params[:category_id])
#subcategory = Subcategory.friendly.find(params[:subcategory_id])
#product = Product.friendly.find(params[:id])
end
Related
i have this .html
<% #resources.each do |resource| %>
<tr>
<!-- -1 es para mostrar todos los recursos que faltan % -->
<% if (resource.curso_id = params[:id] or params[:id] ="-1") and resource.cantidad>0 %>
<td><%= resource.title %></td>
<td><%= #curso.nombre %></td>
<td><%= #user.name %></td>
<!-- %= image_tag(resource.imagen_url, :width => 190, :height => 190) if resource.imagen.present? % -->
<td><%= resource.cantidad %></td>
<td><%= link_to 'Show ', resource %></td>
and this controller:
def index
if params[:id] != "-1"
#resources = Resource.where(:curso_id => params[:id])
#curso = Curso.find(params[:id])
#user = User.find(#curso.user_id)
else
#resources = Resource.all
# HERE IS THE ERROR. I WANT TO GET THE COURSE BUT I WANT THE FIELD CURSO_ID THAT IS IN RESOURCE TABLE
#cursos = Cursos.find(#resource.curso_id)
#user = User.find(#curso.user_id)
end
end
the part that is above the if works ok. but the part below doesnt work. i want to get an attribute from resource in html and use in my controller. how could it be possible? thank you!
It seems like your model associations are not set up.
class Resource < ActiveRecord::Base
belongs_to :curso
end
class Curso < ActiveRecord::Base
has_many :resources
belongs_to :user
end
class User < ActiveRecord::Base
has_many :cursos
end
After that, you can simply access them in view template:
<% #resources.each do |resource| %>
<% resource.curso %>
<% resource.curso.user %>
<% end %>
Lastly, I'd like to add that using localized names for your model attributes is a real bad practice.
#resource is not defined. You have defined #resources = Resource.all(notice the s).
Plus Resource.all returns an array or objects of type Resource. Please explain what you're trying to achieve.
i'm a beginner in ruby on rails and getting an error i seem not to understand.
under the profile page for the Tradesman, i am trying to call all trades and all listed jobs under the trade. Trade has_many jobs & jobs has_many trades.
TrademanprofilesController:
class TrademanprofilesController < ApplicationController
def show
#user = current_user
end
def jobleads
end
def purchased
end
def memberBenifits
end
def account
end
def editjoblead
#trades = Trade.order(:name)
#jobs = Job.all
if params[:search].present?
#applications = Application.near(params[:search], 100, order: 'distance')
#hash = Gmaps4rails.build_markers(#applications) do |application, marker|
marker.lat application.latitude
marker.lng application.longitude
marker.infowindow application.location
marker.infowindow application.trade.name
end
else
#applications = Application.all
end
#applications_trades = #applications.group_by { |t| t.trade_id } end end
The views page which is a partial being called elsewhere. _trademanprofile_skills.html.erb:
<table>
<thead>
<tr>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #trades.each do |trade| %>
<tr>
<td>
<%= trade.name %></br>
<ul><% #trade.jobs.each do |job| %></ul>
<li><%= job.name %></li>
<% end %>
</td>
<td><%= link_to 'Show', trade %></td>
</tr>
<% end %>
</tbody>
</table>
model: Trade.rb
class Trade < ActiveRecord::Base
attr_accessible :name, :job_ids
has_many :applications
has_many :jobs, through: :applications
end
model: Job.rb
class Job < ActiveRecord::Base
attr_accessible :name, :trade_ids
has_many :applications
has_many :trades, through: :applications
end
The error i get:
NoMethodError in Trademanprofiles#editjoblead
undefined method `jobs' for nil:NilClass
and highlights this line:
<ul><% #trade.jobs.each do |job| %></ul>
<li><%= job.name %></li>
<% end %>
i tried the below but did not work
<% #trades.each do |trade| %>
<%= trade.name %>
<%= trade.jobs %>
<% end %>
i got this displayed:
#<Job::ActiveRecord_Associations_CollectionProxy:0x00000106b0f1d8>
i also tried the below but did not work
<% #trades.each do |trade| %>
<%= trade.name %>
<%= trade.job_ids %>
<% end %>
but it only returned the id numbers of the jobs under the trade Aerial / Network
Aerial / Network Specialist
[978, 979, 980, 1039, 1040, 1041]
my routes file:
Rails.application.routes.draw do
resources :images
devise_for :users
resources :jobstartdates
resources :budgets
resources :applications do
collection do
get :search
get :search_result
get :business_details
end
end
get 'home/index'
resources :trades
resources :jobs
root to: 'home#index', as: 'home'
resource :trademanprofiles do
get :show
get :jobleads
get :purchased
get :memberBenifits
get :account
get :editjoblead
end
resources :employeenumbers
resources :businesstypes
resources :trademanroles
resources :titles
resources :adverts
resources :distances
i would like the Trade name & the Job names (not the ids) to be displayed. Many thanks an i truly apologise if this is a simple question.
If you look at your method
def editjoblead
#trades = Trade.order(:name) #this will return a collection of trades to you
#jobs = Job.all
#other logic
end
and in your view you have this
<ul>
<% #trade.jobs.each do |job| %></ul>
<li><%= job.name %></li>
<% end %>
First of all you need to correct your html you have closed ul and then using li and secondly you are trying to get a collection on a collection(#trade is a collection and jobs will give you a collection)
You need to do this:
<% #trades.each do |trade| %>
// this will give a single trade present in #trades
<tr>
<td>
<%= trade.name %></br>
<ul>
<% trade.jobs.each do |job| %>
// this will give a job associated with your trade, notice it's trade and not #trade
<li><%= job.name %></li>
<% end %>
</ul>
</td>
<td><%= link_to 'Show', trade %></td>
</tr>
<% end %>
what about your routes.rb file? I thing the error may be in there put like this in your route file
resources :trades do
resources :applications
resources :jobs
end
I have 3 models:
class Thing < ActiveRecord::Base
has_many :products
has_many :shops, through: :products
end
class Product < ActiveRecord::Base
belongs_to :thing
belongs_to :shop
end
class Shop < ActiveRecord::Base
has_many :products
has_many :things, through: :products
end
Shop sales many things. Every shop has its own page with the list of its things. Products table has shop_id, thing_id, things quantity and thing price.
Here is controller:
def show
#shop = Shop.find(params[:id])
end
And view:
<% #shop.things.each do |thing| %>
<%= link_to thing.name, shop_thing_path(id: thing.id, shop_id: #shop.id) %><br>
<%= thing.products.find_by(shop_id: #shop.id).price %><br>
<%= thing.products.find_by(shop_id: #shop.id).quantity %>
<% end %>
I can't understand how to eager load this right. Now i get N * 2 queries (N = things count):
SELECT "products".* FROM "products" WHERE "products"."thing_id" = ? AND "products"."shop_id" = 1 LIMIT 1
def show
#shop = Shop.includes(:things).find(params[:id])
end
Here is the documentation related to eager loading.
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
I tried to go from another point and use #products instead of #shop.things:
Controller:
def show
#shop = Shop.find(params[:id])
#products = #shop.products.includes(:thing).joins(:thing)
end
View
<% #products.each do |product| %>
<tr>
<td><%= link_to product.thing.name, shop_thing_path(id: product.thing_id, shop_id: product.shop_id) %></td>
<td><%= product.price %></td>
<td><%= product.quantity %></td>
</tr>
<% end %>
Now that works. But i still can't understand why
def show
#shop = Shop.includes(:things).find(params[:id])
end
doesn't work.
I'm using the thumbs_up gem in my application and I'm trying to figure out the best way to save votes in my controller while iterating.
Here is my model:
class Vendor < ActiveRecord::Base
has_many :inventory_items
has_many :items, through: :inventory_items
has_many :shopping_lists, through: :inventory_items
acts_as_voteable
end
my current controller:
def vote_for_vendor
# not sure what to put in here
end
def vote_against_vendor
# not sure what to put in here
end
my current view:
<% provide(:title, 'Stores') %>
<table class="table table-condensed table-hover">
<tr>
<th>Name</th>
<th>Address</th>
<th>Favorite?</th>
</tr>
<% #vendors.each do |v| %>
<tr>
<td><%= v.name %></td>
<td><%= v.address %></td>
<td>
<% if current_user.voted_for(v) %>
<%= link_to 'unlike', vote_against_vendor_vendors_path(vendor_id: v.id), :remote => true %>
<% else %>
<%= link_to 'like', vote_for_vendor_vendors_path(vendor_id: v.id), :remote => true %>
<% end %>
</td>
</tr>
</table>
Most of the examples I've seen have used params([]) to pass the relevant information to the controller. I don't really have params because this is just my index page that shows all vendors. How can I save votes using this gem while iterating? Thanks in advance!
Updated Controller w/ help from MrYoshi
class VendorsController < ApplicationController
def index
#vendors = Vendor.all
end
def vote_for_vendor
vendor = Vendor.find(params[:vendor_id])
current_user.vote_for(vendor)
respond_to do |format|
format.js
end
end
def vote_against_vendor
vendor = Vendor.find(params[:vendor_id])
current_user.vote_against(vendor)
respond_to do |format|
format.js
end
end
end
my routes:
resources :vendors do
collection { post :vote_for_vendor }
collection { post :vote_agaist_vendor }
end
Current Server Error
Started GET "/vendors/vote_for_vendor?vendor_id=4" for 127.0.0.1 at 2013-09-06 10:07:29 -0700
AbstractController::ActionNotFound (The action 'show' could not be found for VendorsController):
...........
Rendered /Users/#Myname/.rvm/gems/ruby-2.0.0-p195/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/unknown_action.erb within rescues/layout (0.5ms)
I give you the start of what you want, and you will be able to do the rest by yourself I think:
View:
<% if current_user.voted_for(v) %>
<%= link_to 'unlike', vote_against_vendor_vendors_path(vendor_id: v.id), :remote => true %>
<% else %>
<%= link_to 'like', vote_for_vendor_vendors_path(vendor_id: v.id), :remote => true %>
<% end %>
Controller:
def vote_for_vendor
vendor = Vendor.find(params[:vendor_id])
current_user.vote_for(vendor)
render :nothing => true
end
And the vote_against is pretty simple to guess now that you have this one above ;)
For your 'current server error' (AbstractController::ActionNotFound (The action 'show' could not be found for VendorsController):), you need to add a member route to your config/routes.rb file, like this:
resources :vendors do
member do
post 'vote_for_vendor'
post 'vote_against_vendor'
end
end
You are currently using collection routes which are for resources that don't need a particular ID to work. I highly recommend reading the Rails Guide on routes:
Rails Guide Documentation on Routes
Hello I'm having 2 objects the one events and the other one categories. I want to put the categories in the layout of the events. i tried but i;m getting an error message
Showing layouts/events.html.erb where line #40 raised:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
<% for category in #categories %>
<li><%=h category.name %>
<ul>
<% for subcategory in #subcategories %>
<% if subcategory.category_id == category.id %>
<li><%=h subcategory.name %></li>
<% end %>
<% end %>
</ul>
</li>
<% end %>
events_controller
def index
#subcategories = Subcategory.find(:all, :order=>"category_id , name")
#categories = Category.find(:all)
#events = Event.find(:all)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #events }
end
end
class Subcategory < ActiveRecord::Base
belongs_to:category
has_many:events
end
class Event < ActiveRecord::Base
belongs_to:subcategory
end
class Category < ActiveRecord::Base
has_many:subcategories
end
my routes
map.root :controller => 'events'
# Index
map.connect '/index/', :controller=>'events', :action=>'index'
map.connect '/index/events/', :controller=>'events', :action=>'index'
map.connect '/index/category/:id', :controller=>'events', :action=>'showallcategoryposts'
# Admin
map.connect '/admin/', :controller=>'events', :action=>'adminindex'
map.connect '/admin/events/new', :controller=>'events', :action=>'new'
map.connect '/admin/category/', :controller=>'subcategories', :action=>'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
I'm using Instant Rails 2.0
how i can correct my code in order to work?
Thank you
Apart from whatever problem you have... IMHO, the code looks quite compromising.
Following are the things, which shouldn't be done the way they are currently:
Building the URLs manually like href="/index/category/<%=h subcategory.id %>" But I can't say much on it to correct it without knowing which Rails version you are on and without seeing your routes.rb
Controller Code is incorrect
Model code also needs improvements
Models should look like this:
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :events, :order => "created_at desc"
end
class Event < ActiveRecord::Base
belongs_to :subcategory
end
class Category < ActiveRecord::Base
has_many :subcategories, :order => "name"
end
EventsController should be like this:
def index
#categories = Category.all(:order => "name", :include => {:subcategories => [:events]})
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #categories }
end
end
And your view should look like:
<% unless #categories.empty? %>
<% #categories.each do |category| %>
<li>
<%=h category.name %>
<ul>
<% category.subcategories.each do |subcategory| %>
<li>
<%=h subcategory.name %>
</li>
<% end %>
</ul>
</li>
<% end %>
<% else %>
Sorry, no events found!
<% end %>
I hope this code will fix your bugs as well.
Please try it.
NOTE: More improvements required in views, depending on your Rails version and your routes.rb ... you should use the path/url methods like category_path(category) etc.
You didn't post your model code. I wonder if you're taking advantage of ActiveRecord associations. If you were, you wouldn't need anything more than #events. You could do stuff like:
<% #events.each do |event| %><br/>
<% event.categories.each do |category| %>
stuff
<% end %>
<% end %>
Check out this guide.
I am pretty sure EventsController#index is rendering views/events/index.html.erb, and layouts/events.html.erb knows nothing of #categories which is set for use in said rendering. Where do you render layouts/events.html.erb? Try placing this below your class definition:
layout 'events'
Also, it is worth checking out what #categories is within the controller with a Rails.logger.debug. Is it nil there as well?