I'm trying to link each image from my index page (products_path) to my show page.
In my controller I currently have:
class ProductsController < ApplicationController
before_action :find_product, only: [:show]
def index
#products = Dir.glob("#{Rails.root}/app/assets/images/*.jpg")
end
def show
end
private
def find_product
#product = Product.find(params[:id])
end
end
And in my index view page:
<% Dir[File.join("public/assets", "*.jpg")].each do |file| %>
<%= link_to image_tag file.gsub('public', ''), product_path(#product), class: 'img-responsive col-lg-3' %>
<% end %>
This results in an error which I've been trying to fix for quite a while. I hope anyone has some experience with this error.
No route matches {:action=>"show", :controller=>"products", :id=>nil} missing required keys: [:id]
I thought 'products' was empty but when I check the console, there are a few Product attributes with images in them.
#products = Dir.glob("#{Rails.root}/app/assets/images/*.jpg")
What is this?
Why are you filling an instance variable with the glob of all the images in your assets/images directory? You can call that in your view.
You shouldn't have this in the controller; you shouldn't even have it because it's a bad pattern (not object orientated).
--
No route matches {:action=>"show", :controller=>"products", :id=>nil} missing required keys: [:id]
This error is caused by you're calling a link_to without an appropriate id to send into the request. I appreciate you're sending #product; it's either that this has not been invoked properly, or you're calling it incorrectly.
The problem here is that you're passing #product without actually setting it... before_action :find_product, only: [:show] - the index action won't have #product available.
This problem would be fixed with my recommendation below. Or simply, you have to populate the link_to with either an id value, or an object.
Fix
You should be attaching your images to your Product model.
You can use Paperclip or Carrierwave to do this:
#app/models/product.rb
class Product < ActiveRecord::Base
has_attached_file :image #-> paperclip implementation
end
This will allow you to upload images for the model itself (I can write more about this if required).
You'd then be able to use the OOP pattern:
#app/controllers/products_controller.rb
class ProductsController < ApplicationController
def index
#products = Product.all
end
end
Then in your view:
#app/views/products/index.html.erb
<% #products.each do |product| %>
<%= product.name %>
<%= image_tag product.image.url %>
<% end %>
Related
Before getting into details I have read through these posts to try to find the solution without success : one, two, three
That being said: I am [new and] building an ecomm site for selling secondhand clothing, shoes and decor items.
My structure has only one Product model and associated controller and table. Each 'product' has one of three different main categories, which is what I am using to differentiate and create 3 different URLs.
My routes look like this:
Rails.application.routes.draw do
root to: 'pages#home'
get 'clothing', to: 'products#clothing'
get 'clothing/:id', to: 'products#show'
get 'shoes', to: 'products#shoes'
get 'shoes/:id', to: 'products#show'
get 'home', to: 'products#home'
get 'home/:id', to: 'products#show'
get 'products/new', to: 'products#new'
post 'products', to: 'products#create'
end
My products_controller looks like this:
class ProductsController < ApplicationController
before_action :set_all_products
before_action :set_one_product, only: [:show]
def shoes
#all_shoe_products = #all_products.where(main_category_id: MainCategory.find_by_name("shoes").id)
end
def clothing
#all_clothing_products = #all_products.where(main_category: MainCategory.find_by_name("clothes").id)
end
def home
#all_home_products = #all_products.where(main_category: MainCategory.find_by_name("housewares").id)
end
def show
end
def new
#new_product = Product.new
end
private
def set_one_product
#product = Product.find(params[:id])
end
def set_all_products
#all_products = Product.all
end
end
And when writing <%= link_to clothing_path(product) %> ('product' being the placeholder in an .each loop), I get a path: root/clothing.[:id] and not root/clothing/[:id]
I know I am making a convention error, and trying to have 3 different URLs within the same controller may be where I am gong wrong.
Note: manually entering root/clothing/[:id] in the address bar does return a product correctly.
When you do this:
get 'clothing', to: 'products#clothing'
get 'clothing/:id', to: 'products#show'
in your routes.rb, it creates these routes (which you can see by doing rake routes in your console):
clothing GET /clothing(.:format) products#clothing
GET /clothing/:id(.:format) products#show
As you can see, clothing_path routes to /clothing, not /clothing/:id. So, when you do:
<%= link_to clothing_path(product) %>
rails appends the id as .id (which is what you're experiencing).
#jvillian explains the cause of the issue well here, though I'd like to propose a slight refactor as a solution.
This might be a little more work, though you'd likely be better off with seperate controllers for shoes, clothing and home, and following a RESTful design. That would allow you to use resources in your routes file.
For example, your shoes_controller.rb would be like the following:
class ShoesController < ApplicationController
before_action :set_all_products
before_action :set_one_product, only: [:show]
def index
#all_shoe_products = #all_products.where(main_category_id: MainCategory.find_by_name("shoes").id)
end
def show
end
private
def set_one_product
#product = Product.find(params[:id])
end
def set_all_products
#all_products = Product.all
end
end
And then the routes to define them would be:
resources :shoes, only: [:index, :show]
You follow this pattern for the other resources and you'll have nicely segregated code be following good Rails conventions.
This will generate the routes as you're after:
shoes GET /shoes(.:format) shoes#index
shoe GET /shoe/:id(.:format) shoes#show
That will resolve your issue and give you a nicely designed app - there's also opportunity to extrapolate some of the code shared between the new controllers, though that sounds like a follow up task :)
Hope this helps - let me know if you've any questions or feedback.
I found a solution, though seems a bit of a logic mystery to me why it's working.
In routes.....
get 'clothing', to: 'products#clothing'
get 'clothing/:id', to: 'products#show', as: 'clothing/item'
In the index page....
<%= link_to clothing_item_path(product) do %>
This yields the right URL structure: root/clothing/[:id]
While testing this I was expecting: root/clothing/item/[:id]
...though I prefer the result over my expectation
I think what you want is parameterized routes, like this:
get ':product_line', to: 'products#index'
get ':product_line/:id', to: 'products#show'
This would allow you to create any number of custom product lines without ever having to define new methods in your controller. Assuming there is a product_line attribute on your Product model, the controller would look like this:
class ProductsController < ApplicationController
def index
#product_line = params[:product_line]
#products = Product.where(product_line: #product_line)
end
def show
#product_line = params[:product_line]
#product = Product.find(params[:id])
end
end
And your views/products/index.html.erb would look like this:
<p id="notice"><%= notice %></p>
<h1><%= #product_line %></h1>
<table>
<thead>
<tr>
<th>Description</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
<% #products.each do |product| %>
<tr>
<td><%= product.description %></td>
<td><%= product.price %></td>
<td><%= link_to 'Show', "#{#product_line}/#{product.id}" %></td>
</tr>
<% end %>
</tbody>
</table>
Note that the link_to can no longer use a Rails helper method to generate the url. You'd have to do that yourself.
The beauty of this approach is that users could type in ANY product line in the URL. If you had that product line (like say 'sporting_goods'), go ahead and display it. If not, render a page thanking them for their interest and log the fact that someone requested that product line so you can guage interest as you expand your offerings.
Plus, it's RESTful! Yay!
The Rails way of solving this is by creating a nested resource:
resources :categories do
resources :products, shallow: true
end
This nests the collection routes so that you get GET /categories/:category_id/products.
While this might not be as short as your vanity routes it is much more versatile as it will let you show the products for any potential category without bloating your codebase.
You would setup the controller as so:
class ProductsController < ApplicationController
before_action :set_category, only: [:new, :index, :create]
# GET /categories/:category_id/products
def index
#products = #category.products
end
# GET /categories/:category_id/products/new
def new
#product = #category.products.new
end
# POST /categories/:category_id/products
def new
#product = #category.products.new(product_params)
# ...
end
# ...
private
def set_category
#category = MainCategory.includes(:products)
.find_by!('id = :x OR name = :x', x: params[:id])
end
end
You can link to products of any category by using the category_products_path named path helper:
link_to "#{#category.name} products", category_products_path(category: #category)
You can also use the polymorphic path helpers:
link_to "#{#category.name} products", [#category, :products]
form_for [#category, #product]
redirect_to [#category, :products]
If you want to route the unnested GET /products and nested GET /categories/:category_id/products to different controllers a neat trick is to use the module option:
resources :products
resources :categories do
resources :products, only: [:new, :index, :create], module: :categories
end
This will route the nested routes to Categories::ProductsController.
I am getting an undefined method stripe_managed_accounts_path when trying to create a new resource via typical rails forms. Below is my code, I am dumbfounded, cannot figure it out.
Controller
class StripeManagedAccountsController < ApplicationController
before_action :authenticate_printer!
def new
#stripe_managed_account = StripeManagedAccount.new(printer_id: current_printer.id)
end
end
model
class StripeManagedAccount < ActiveRecord::Base
belongs_to :printer
end
views/new
<h1>Create New Stripe Managed Account</h1>
<%= render 'form' %>
view/form
<h5>inside the form</h5>
<%= form_for #stripe_managed_account do |f| %>
<% end %>
routes
resources :printers, only: [:show, :edit, :update] do
resources :stripe_managed_accounts
end
error
`undefined method 'stripe_managed_accounts_path' for #<#<Class:0x007fc627d342b8>:0x007fc62b36e108>`
routes
printer_stripe_managed_accounts GET /printers/:printer_id/stripe_managed_accounts(.:format) stripe_managed_accounts#index
POST /printers/:printer_id/stripe_managed_accounts(.:format) stripe_managed_accounts#create
new_printer_stripe_managed_account GET /printers/:printer_id/stripe_managed_accounts/new(.:format) stripe_managed_accounts#new
edit_printer_stripe_managed_account GET /printers/:printer_id/stripe_managed_accounts/:id/edit(.:format) stripe_managed_accounts#edit
printer_stripe_managed_account GET /printers/:printer_id/stripe_managed_accounts/:id(.:format) stripe_managed_accounts#show
PATCH /printers/:printer_id/stripe_managed_accounts/:id(.:format) stripe_managed_accounts#update
PUT /printers/:printer_id/stripe_managed_accounts/:id(.:format) stripe_managed_accounts#update
DELETE /printers/:printer_id/stripe_managed_accounts/:id(.:format) stripe_managed_accounts#destroy
and it is highliting this line <%= form_for #stripe_managed_account do |f| %>
I have grepped the entire code base for stripe_managed_accounts_path and it is no where. I am at odds end...
UPDATE:::
If I add that route it disappears??? Why is it looking for that route. Is it becasue of how I named my fodlers, etc??
You're nesting stripe_managed_accounts inside printers on your routes file. If you take a look at the output of rake routes, you can see that there isn't a path for stripe_managed_accounts_path.
You can either use the shallow option on the stripe_managed_accounts resource or adjust your form to include the printer which the managed account will belong to.
#controller
class StripeManagedAccountsController < ApplicationController
before_action :authenticate_printer!
def new
#stripe_managed_account = current_printer.build_stripe_managed_account
end
def create
current_printer.stripe_managed_accounts.create stripe_managed_account_params
# handle response
end
def stripe_managed_account_params
params.require(:stripe_managed_account).permit([list of attributes])
end
end
#form
<h5>inside the form</h5>
<%= form_for [current_printer, #stripe_managed_account] do |f| %>
<% end %>
That will generate the proper url, nesting the stripe_managed_account inside the current printer.
For has_one association reference http://guides.rubyonrails.org/association_basics.html#has-one-association-reference
For your context: This is my first attempt to create a app. I have just started coding:-).
I am trying to get a simple CRUD setup to work.
Now i'm having two problems i can't get my head around:
My entries don't show up on my index page. it gives te following error: 'undefined method `title' for nil:NilClass'. The model contains the following columns:
string :title,text :forecast, date :review_date
If i go to decisions/edit it gives me the following error: 'Couldn't find Decision with 'id'=edit'
This is my code:
Controller:
class DecisionsController < ApplicationController
before_action :find_decision, only: [:show, :edit, :update]
def index
# gets all rows from decision table and puts it in #decision variable
#decisions = Decision.all
end
def show
# find only the decision entry that has the id defined in params[:id]
#decision = Decision.find(params["id"])
end
# shows the form for creating a entry
def new
#decision = Decision.new
end
# creates the entry
def create
#decision = Decision.new(decision_params)
if #decision.save
redirect_to #decision
else
render 'new'
end
end
# shows the form for editing a entry
def edit
#decision = Decision.find(params["id"])
end
# updates the entry
def update
end
def destroy
end
private
def find_decision
#decision = Decision.find(params["id"])
end
def decision_params
params.require(:decision).permit(:title, :forecast, :review_date)
end
end
index view
<h1>Hello World ^^</h1>
<% #decisions.each do |descision| %>
<p><%= #decision.title %></p>
<% end %>
routes.rb
Rails.application.routes.draw do
resources :decisions
root 'decisions#index'
end
I have been working on these two all morning but i can't figure it out. I would be a great help if you guys can take a look for me.
I have just started coding
Welcome!!
My entries don't show up on my index page.
I'm sure you mean decisions, right?
If so, you have to remember that if you're calling a loop in Ruby, you'll need some conditional logic to determine if it's actually populated with any data before trying to invoke it:
#app/views/decisions/index.html.erb
<% if #decisions.any? %>
<% #decisions.each do |decision| %>
<%= content_tag :p, decision.title %>
<% end %>
<% end %>
This will have to be matched by the appropriate controller code:
#app/controllers/decisions_controller.rb
class DecisionsController < ApplicationController
before_action :find_decision, only: [:show, :edit, :update, :destroy]
def index
#decisions = Decision.all
end
def show
end
def new
#decision = Decision.new
end
def create
#decision = Decision.new decision_params
#decision.save ? redirect_to(#decision) : render('new')
end
def edit
end
def update
end
def destroy
end
private
def find_decision
#decision = Decision.find params["id"]
end
def decision_params
params.require(:decision).permit(:title, :forecast, :review_date)
end
end
This will give you the ability to call #decisions and #decision in your views depending on which route you're accessing.
An important point is that when you say...
decisions/edit it gives me the following error: Couldn't find Decision with 'id'=edit'
... the issue is caused by the way in which Rails routing is handled:
Because Ruby/Rails is object orientated, each set of routes corresponds to either a collection of objects, or a member object. This is why routes such as edit require an "id" to be passed - they're designed to work on member objects.
As such, when you access any "member" route (decisions/:id, decisions/:id/edit), you'll have to provide an id so that Rails can pull the appropriate record from the db:
#app/views/decisions/index.html.erb
<% if #decisions.any? %>
<% #decisions.each do |descision| %>
<%= link_to "Edit #{decision.title}", decision_edit_path(decision) %>
<% end %>
<% end %>
I can explain a lot more - the above should work for you for now.
I have a Slider model in my project and it has a lot of polymorphic associations with other model like Product, Manufacturer, Article and etc.
So, when I use 'show' action with one of the models I also show related Slider. It's ok. But sometimes I need to show Slider with 'index' action.
What is the best way to link some of the sliders to actions, not to other models?
UPDATE
routes
resources :products, :articles, :industries, :manufacturers, only: [:index, :show]
Product controller
class ProductsController < ApplicationController
load_resource
# GET /products
# GET /products.json
def index
#catalog = Product.by_type_and_manufacturer
end
# GET /products/1
# GET /products/1.json
def show
#page_slider = #product.slider
end
end
So in 'show' action I just use product.slider to get related Slider instance. But I want to show another slider for all products by index action.
In that case, what you're trying to do is not possible. You cannot create a relation to a controller action. What you need to do is link the relation's controller action, rather than trying to create a relation to the controller action. A model can only be related to another model (you cannot has_many index, show, delete, etc...)- In other words, call up the data for the relation, and link to that relation's controller action in the view.
example:
#Models:
class Page < ActiveRecord::Base
has_many :sliders
end
class Slider < ActiveRecord::Base
belongs_to :page
end
#Controllers
class PagesController < ApplicationController
def index
#pages = Page.all # lists all pages
end
def show
#page = Page.find(params[:id]) # simplified, this will probably make use of strong params in your actual code
#sliders = #page.sliders # all sliders related to the page
end
# if you would like to show a page that just has all sliders for a specific page and not the page itself...
def show_page_sliders # you will have to create a route and view for this manually
#page = Page.find(params[:id]) # simplified, this will probably make use of strong params in your actual code
#sliders = #page.sliders # all sliders related to the page
# note that this controller action is identical to the show action, because the data we're going to need is the same- the difference comes in the view
end
end
class SlidersController < ApplicationController
def index
#sliders = Slider.all
end
def show
#slider = Slider.find(params[:id])
end
end
# Views
# page#index
<% #pages.each do |p| %>
...
page listing code goes here. if you want to list the sliders for each page on the index...
<% p.sliders.each do |s| %>
...
individual slider info goes here
...
<% end %>
...
<% end %>
# pages#show
<%= #page.name %>
<%= #page.content %> <!-- or whatever data you have for page -->
# since here we are showing a singular page, we can just use our #page instance variable to list out the sliders
<% #page.sliders do |s| %>
...
Slider listing code goes here
...
<% end %>
# pages#show_sliders
<!-- this is identical to the page#show view, minus the actual page info, and with the addition of a link back to the parent page -->
<%= link_to "Back to page", page(s.page_id) %>
<% #page.sliders do |s| %>
...
Slider listing code goes here
<!-- you can link to any path from the slider listing -->
<%= link_to "Show", slider(s.id) %>
<%= link_to "Edit", edit_slider_path(s.id) %>
<%= link_to "Delete", delete_slider_path(s.id) %>
...
<% end %>
#######################UPDATE#############################
# to define one slider per controller action
class PagesController < ApplicationController
def index
#pages = Page.all
# you need to add a "controller_action" column to your Slider model
#slider = Slider.find_where(controller_action: "pages#index")
end
def show
#page = Page.find(params[:id])
#slider = Slider.find_where(controller_action: "pages#show")
end
# etc ...
I've an issue with the paths in the views and I don't know how to solve it.
I've "categories" that has_many "posts" and "posts" that belongs_to "categories".
1.- I want to show on home page the truncate last post of an specific category (the ID number "1"). Then I want that post to link to the show post path but I get this error:
"Unknow Action
The action 'index' could not be found for PostsController"
I think I've my paths wrong because I don't need the index view because I'm only going to show that specific post. So, I think that category_posts_path(#last_post) is not the right path (I don't know where to look for more info about making the route path in the views...). Actually, the browser is showing me that is looking for the "2" category when it is a post of the "1" category...? What am I doing wrong?
This is the browser route:
http://localhost:3000/en/categories/2/posts
This is my views/categories/home.html.erb file:
<div class="post_details">
<h2><%= #last_post.title %></h2>
<%= image_tag #last_post.image(:header), class: "post_image" %>
<p><%= truncate #last_post.body, length: 100 %></p>
<p class="button"><%= link_to "READ MORE", category_posts_path(#last_post) %></p>
</div>
2.- I have another path problem in the views/categories/show.html.erb file. I have a loop to show all the post of one specific category, but when I link in some post (to show it) there is the "index" error again:
"Unknow action
The action 'index' could not be found for PostsController"
This is the browser route:
http://localhost:3000/en/categories/1/posts
This is the views/categories/show.html.erb file:
<div class="post_details">
<h2><%= link_to post.title, category_posts_path(post) %></h2>
<%= image_tag post.image(:header), class: "post_image" %>
<p><%= post.body %></p>
</div>
This is the categories_controller.rb file:
class CategoriesController < ApplicationController
before_action :get_categories
def index
end
def show
#category = Category.find(params[:id])
end
def home
if params[:set_locale]
redirect_to root_url(locale: params[:set_locale])
else
#category = Category.find_by_id(1)
#last_post = #category.posts.order("created_at desc").first
end
end
def get_categories
#categories = Category.all.order("rank asc, name asc")
end
end
This is my posts_controller.rb file:
class PostsController < ApplicationController
def show
#category = Category.find(params[:category_id])
#post = #category.posts.find(params[:id])
end
end
This is my route.rb file:
scope '(:locale)' do
resources :categories do
resources :posts
end
resources :contacts
root 'categories#home'
get "/contact" => "contacts#new"
# static pages
get "/investment" => "contents#investment"
get "/partner-with-us" => "contents#partner", as: "partner"
get "/our-companies" => "contents#companies", as: "companies"
get "/site-map" => "contents#sitemap", as: "sitemap"
get "/terms-and-conditions" => "contents#terms", as: "terms"
get "/privacy" => "contents#privacy"
end
When you are nesting routes you should always consider what is the parent and whats a child in given route. Since your paths don't know anything about your associations you have to explicitly define every object in the nesting.
I.e. since you nested posts in categories linking to last post in given category would look like this:
category_post_path(#category, #last_post)
(I think you have also a typo there - category_posts_paths - which links to posts index index - hence the error. Use category_post_path. instead, and give it both parent category and the post.
You can run rake routes to see exact information on paths (or go to http://localhost:3000/rails/info/routes )