我有一个应用程序,用户可以在其中创建产品。在产品页面上,我有一个编辑链接和一些文字。
当我创建一个新产品时。我明白了
路由错误没有路由匹配 {:action=>"edit", :controller=>"products"}
但是,当我检查我的数据库时,产品已创建,我可以正常查看页面。包括编辑按钮。
产品页面 (haml)
= @product.name
%br
= @product.description
%br
- if current_user.admin || @product.user_id == current_user.id
= link_to 'Edit', edit_product_path
= link_to 'Delete', @product, method: :delete, data: { confirm: "Are you sure?" }
产品控制器
class ProductsController < ApplicationController
before_filter :require_login
before_filter :current_user, only: [:create, :destory]
before_filter :admin_and_author, only: [:destory, :edit]
before_filter :admin_user, only: :index
def new
@product = Product.new
@photo = Photo.new
4.times{ @product.photos.build }
end
def create
@product = current_user.products.new(params[:product])
@photo = current_user.photos.new(params[:photo])
if @product.valid?
@product.save
@photo.product_id = @product.id
@photo.save
render "show", :notice => "Sale created!"
else
render "new", :notice => "Somehting went wrong!"
end
end
def show
@product = Product.find(params[:id])
end
def edit
@product = Product.find(params[:id])
@photo = @product.photos
end
private
def correct_user
@product = current_user.products.find_by_id(params[:id])
redirect_to root_url if @product.nil?
end
def require_login
unless current_user
redirect_to root_url
end
end
def admin_and_author
@product = current_user.products.find_by_id(params[:id])
redirect_to root_url if @product.nil? || current_user.admin
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
应用控制器
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
private
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
def admin_and_user
if current_user.id == 1 || current_user.admin
else
redirect_to(root_path)
end
end
end
创建产品页面(haml)
%h1
create item
= form_for @product,:url => products_path, :html => { :multipart => true } do |f|
%p
= f.label :name
= f.text_field :name
%p
= f.label :description
= f.text_field :description
%p
= f.fields_for :photos do |fp|
=fp.file_field :image
%br
%p.button
= f.submit
耙路线
products GET /products(.:format) products#index
POST /products(.:format) products#create
new_product GET /products/new(.:format) products#new
edit_product GET /products/:id/edit(.:format) products#edit
product GET /products/:id(.:format) products#show
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format) products#destroy