Scoping resource routes in Rails 4 - ruby-on-rails

I have a resources :shops
which results in a /shops, /shops/:id, etc
I know I can scope collection or members with
resources :shops do
scope ":city" do
# collection and members
end
end
or do it before with
scope ":city" do
resources :shops
end
But I can't figure out how to make the route be on all members (including the standard REST ones) and collection, like so
/shops/:city/
/shops/:city/:id

As per your use case and question, you are trying to have logically wrong routes. You have shops within the city, NOT city within the shop.
Firstly you should normalize your database. You should create another table cities and replace your city attributes with city_id in shops table.
You need has_many and belongs_to association between cities and shops.
# Models
class City < ActiveRecord::Base
has_many :shops
... # other stuff
end
class Shop < ActiveRecord::Base
belongs_to :city
... # other stuff
end
Routes
resources :cities do
resources :shops
end
It will generate routes like:
POST /cities/:city_id/shops(.:format) shops#create
new_city_shop GET /cities/:city_id/shops/new(.:format) shops#new
edit_city_shop GET /cities/:city_id/shops/:id/edit(.:format) shops#edit
city_shop GET /cities/:city_id/shops/:id(.:format) shops#show
PATCH /cities/:city_id/shops/:id(.:format) shops#update
PUT /cities/:city_id/shops/:id(.:format) shops#update
DELETE /cities/:city_id/shops/:id(.:format) shops#destroy
Logically, these routes will show that in which city the particular shop exists.

Namespace
You may wish to consider including a namespace
Since you're trying to pull up the cities for shops (IE I imagine you want to show shops in Sao Paulo), you'd be able to do this:
#config/routes.rb
namespace :shops do
resources :cities, path: "", as: :city, only: [:index] do #-> domain.com/shops/:id/
resources :shops, path: "", only: [:show] #-> domain.com/shops/:city_id/:id
end
end
This will allow you to create a separate controller:
#app/controllers/shops/cities_controller.rb
Class Shops::CitiesController < ApplicationController
def index
#city = City.find params[:id]
end
end
#app/controllers/shops/shops_controller.rb
Class Shops::ShopsController < ApplicationController
def show
#city = City.find params[:city_id]
#shop = #city.shops.find params[:id]
end
end
This will ensure you're able to create the routing structure you need. The namespace does two important things -
Ensures you have the correct routing structure
Separates your controllers

Related

I need a fresh pair of airs for this error here: "undefined method `items' for #<Order:0x00007f93d361b390>"

I am learning Ruby and building a shopping cart site, for book.
I am trying to create my orders. Was following the tutorial below.
https://www.youtube.com/watch?v=orDmqI-dlCo&list=PLebos0ZZRqzeT7XBTYwL9JGN1PwoZVB9p&index=4
The Error happens when I click on Add order to basket, the problem is that "items" is only referrenced on the routes and not on the tables, I have order_items table in my schema, I must be tired, but if you can help will appreciate.
book = Book.find(book_id)
order_item = order.items.find_or_create_by(
book_id: book_id
)
Order Items Controller
class OrderItemsController < ApplicationController
def create
current_bag.add_item(
book_id: params[:book_id],
quantity: params[:quantity]
)
redirect_to bag_path
end
end
Shopping Bag Controller
class ShoppingBag
def initialize(token:)
#token = token
end
def order
#order ||= Order.find_or_create_by(token: #token) do | order|
order.sub_total = 0
end
end
def add_item(book_id:, quantity: 1)
book = Book.find(book_id)
order_item = order.items.find_or_create_by(
book_id: book_id
)
order_item.price = book.price
order_item.quantity = quantity
order_item.save
end
end
Routes
Rails.application.routes.draw do
root "books#index"
resources :line_items
get '/bag', to: 'order_items#index'
resources :order_items, path: '/bag/items'
# resources :locations
resources :books
devise_for :users, controllers: {registrations: "registrations"}
resources :pricing, only: [:index]
resources :subscriptions
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
My Order.rb file
class Order < ApplicationRecord
end
The tutorial probably added the needed associations between the first and second video (like mentioned in part 1 timestamp 36:20).
With your current code I would assume they are as follows:
class Order < ApplicationRecord
has_many :items, class_name: 'OrderItem'
# ...
end
class OrderItem < ApplicationRecord
belongs_to :order
# ...
end
For this to work the order_items table must have an order_id column (with the same type as the id column of the orders table).
For more info about associations check out the Active Record Associations guide.

Change wildcard route based off an array from Rails 3 to Rails 4

In Rails 3, I have these:
# shop.rb
class Shop < ActiveRecord::Base
TYPES = %w(cafe restaurant)
end
# shops_controller.rb
class SpotsController < ApplicationController
def cafe
end
def restaurant
end
end
# routes.rb
resources :shops do
resources :reviews, :photos
member do
get *Shop::TYPES
end
end
The idea is to generate get routes based off the Shop::TYPES array:
get :cafe
get :restaurant
In any case when I create another new type in Shop, I won't have to update my routes.
I am upgrading to Rails 4. What is the equivalent to get *Shop::TYPES, because I couldn't find the answer?
You can Try this
resources :shops do
resources :reviews, :photos
member do
get 'cafe'
get 'restaurant'
end
end
You can also try this Link

How to Create Basket of Shop site model in rails 4?

My project is about an online shopping site, using Ruby on Rails to buy phones.
My Database is User, Product, Phone.
I'm trying to create Basket model.
My route:
resources :products do
resources :phone do
resources :baskets
end
end
And my Code is:
class User < ActiveRecord::Base
has_many :baskets
end
class Phone < ActiveRecord::Base
belongs_to :product
has_many :baskets
end
class Basket < ActiveRecord::Base
belongs_to :user
belongs_to :phone
end
When i in the Show action of Product,it Show name of Product and index Phones in this Product,i want to add 1 Phone to Basket,the error is :
No route matches {:action=>"new", :controller=>"baskets", :id=>"38", :product_id=>"30"} missing required keys: [:phone_id]
I think the problem is :
http://localhost:3000/products/30/phone/38
It's Product_id = 30,but not Phone_id = 30,in here just is Id = 30.
Someone could help me fix it !
resources :products do
resources :phone do
resources :baskets
end
end
means you have to have route like this:
/products/:product_id/phones/:phone_id/baskets/:basket_id(.:format)
Which means, that in link_to you should pass the phone_id as well:
link_to 'show basket' product_phone_basket_path(product_id: #product.id, phone_id: #phone.id, basket_id: #basket.id)
link_to 'New basket' new_product_phone_basket_path(product_id: #product.id, phone_id: #phone.id)
Regardless of whether you got it working (I upvoted #Andrey's answer), you'll want to consult your routing structure.
Resources should never be nested more than 1 level deep. docs
--
In your case, I am curious as to why you have phones nested inside products. Surely a phone is a product?
Further, why are you including resources :baskets? Surely the basket functionality has nothing to do with whether you're adding a product, phone, or anything else?
I would personally do the following:
resources :products, only: [:index, :show] do
resources :basket, path:"", module: :products, only: [:create, :destroy] #-> url.com/products/:product_id/
end
#app/controllers/products/basket_controller.rb
class Products::BasketController < ApplicationController
before_action :set_product
def create
# add to cart
end
def destroy
# remove from cart
end
private
def set_product
#product = Product.find params[:product_id]
end
end
I've implemented a cart (based on sessions) before (here).
I can give you the code if you want; I won't put it here unless you want it. It's based on this Railscast.

Rails way for different views of a resource

Let us assume we have two resources: auctions and bids, and that an auction has many bids possibly modeled as nested resources. There are two possible collections of bids: the collection of all bids in the rails application and the collection of bids associated with a particular auction. If the user wants to access both of these collections, how would we model this in the controllers?
One possible solution is to construct two routes (auctions/:auction_id/bids and bids/) that point to the BidsController#index action and branch according to the presence of params[:auction_id]. One can imagine that the situation worsens if a bid also belongs to a user, thus creating another conditional on our BidsController checking for params[:user_id] to return the collection of bids associated to a given user. What is the rails way of dealing with this problem?
The out of the box solution for dealing with nested resources is to handle it in child resource controller:
Sampleapp::Application.routes.draw do
resources :bids
resources :users do
resources :bids # creates routes to BidsController
end
resources :auctions do
resources :bids # creates routes to BidsController
end
end
class BidsController < ApplicationController
before_action :set_bids, only: [:index]
before_action :set_bid, only: [:show, :update, :destroy]
def index
end
# ... new, create, edit, update, destroy
def set_bid
# when finding a singular resources we don't have to give a damn if it is nested
#bid = Bids.find(params[:id])
end
def set_bids
#bids = Bids.includes(:user, :auction)
if params.has_key?(:user_id)
#bids.where(user_id: params[:user_id])
elsif params.has_key?(:auction_id)
#bids.where(auction_id: params[:auction_id])
end
#bids.all
end
end
The advantage here is that you get the full CRUD functionality with very little code duplication.
You could however quite simply override the index routes if you want to have different view templates, or do different sorting etc.
Sampleapp::Application.routes.draw do
resources :bids
resources :users do
member do
get :bids, to: 'users#bids', :bids_per
end
resources :bids, except: [:index]
end
resources :auctions do
member do
get :bids, to: 'auction#bids', as: :bids_per
end
resources :bids, except: [:index]
end
end
Another solution would be creating a AuctionsBidsController and defining the route as such:
resources :auctions do
resources :bids, only: [:index], controller: 'AuctionsBids'
resources :bids, except: [:index]
end
You don't necessarily have to involve the bids controller every time you want to display a list of bids. For example, if I were setting up this scenario and wanted to display a list of bids related to a particular auction, I would handle that in the auctions controller, not the bids controller, like so:
class AuctionsController < ApplicationController
...
def show
#auction = Auction.find(params[:id])
#bids = #auction.bids #assuming the bids belong_to your Auction model
end
Then, somewhere in the view app/views/auctions/show.html.erb you can list the bids using the same partial you use in your bids index:
<ul>
<%= render partial: 'bids/bid', collection: #bids %>
</ul>
This is just one way to handle the situation. You could do the same thing with your User model or any other model in your application. The point is that you don't have to involve a model's specific controller every time you want that model to appear in a view.

uninitialized constant -- model within controller

I have an application in which a club has_many locations. Clubs & their locations can only be edited within an admin namespace.
I am trying to pre-load the club into the controller so that all actions deal with that club only.
The routes are nested; however, in the locations controller, it does not find the Club model. What am I doing wrong?
routes.rb
namespace :admin do
resources :clubs do
resources :locations
end
end
club.rb
class Club < ActiveRecord::Base
belongs_to :membership
has_many :users
has_many :locations
#accepts_nested_attributes_for :locations
end
admin/locations_controller.rb
class Admin::LocationsController < ApplicationController
before_filter :load_club
protected
def load_club
#club = Club.find(params[:club_id])
end
end
Also, lastly: What is wrong with my routes that it is not looking for the locations controller in admin/clubs/locations? I'm not sure if that is part of the problem.
from rake routes
admin_club_locations POST /admin/clubs/:club_id/locations(.:format) admin/locations#create
new_admin_club_location GET /admin/clubs/:club_id/locations/new(.:format) admin/locations#new
edit_admin_club_location GET /admin/clubs/:club_id/locations/:id/edit(.:format) admin/locations#edit
admin_club_location PUT /admin/clubs/:club_id/locations/:id(.:format) admin/locations#update
DELETE /admin/clubs/:club_id/locations/:id(.:format) admin/locations#destroy
It probably looks up the Club model within the current Admin namespace. You could try:
def load_club
#club = ::Club.find(params[:club_id])
end

Resources