我在用户,商店和商品之间建立了这样的关联:
user has one store
store has many items
item belongs to store
因此,当我创建商品时,它必须属于当前用户的商店
现在,我以user_1的身份登录,我想搜索user_2的项目。但是,如果我没有创建user_1的商店,它将继续将我重定向到localhost:3000 / stores
在items_controller.rb中:
class ItemsController < ApplicationController
before_action :find_item, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:new, :edit]
def index
if params[:category].blank?
@items = Item.all.order("created_at DESC")
end
if params[:category]
@category_id = Category.find_by(name: params[:category]).id
@items = Item.where(category_id: @category_id).order("created_at DESC")
end
end
def show
end
def new
@store = current_user.store
@item = @store.items.build
@categories = Category.all.map{ |c| [c.name, c.id] }
end
def update
@item.category_id = params[:category_id]
if @item.update(item_params)
redirect_to item_path(@item)
else
render 'edit'
end
end
def create
@store = current_user.store
@item = @store.items.build(item_params)
@item.category_id = params[:category_id]
if @item.save
flash[:success] = "Creating item success"
redirect_to @item
else
render 'new'
end
end
private
def item_params
params.require(:item).permit(:code, :name, :description, :producer, :item_img, :store_id,
:category_id )
end
def find_item
@item = Item.find(params[:id])
end
def find_user
@user = User.find_by(params[:user_id])
end
end
在stores_controller.rb中:
class StoresController < ApplicationController
before_action :find_store, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :find_user
def show
if current_user.store.blank?
redirect_to new
else
@items = Item.where(store_id: @store.id)
end
end
def index
@stores = Store.all.order("created at DESC")
end
def new
@store = current_user.build_store
end
def create
@store = current_user.build_store(store_params)
if @store.save
session[:store_id] = @store.id
flash[:success] = "Creating item success"
redirect_to @store, notice: 'success'
else
render 'new'
end
end
private
def store_params
params.require(:store).permit( :name , :user_id)
end
def find_store
@store = Store.find(params[:id])
end
def find_user
@user = Store.find_by(params[:user_id])
end
end
每当我单击items / show.html.erb中的按钮时,就会引发错误。 在items / show.html.erb中:
<button>see more item from:<%= link_to @item.store.name, store_path(@item.store.id)%></button>
在routes.rb中:
devise_for :users
resources :items
resources :stores
在stores_controller的show方法中,我仍然要在navbar部分中加载current_user的商店,以确保他登录后可以在其商店中添加更多商品。
我仍然是Rails的新手,我正在寻找解决这个问题的方法:-)
答案 0 :(得分:1)
如果商店需要user_id,那么您不需要before_action :find_user
,因为您只需致电store.user
即可获得商店的用户
您似乎需要current_user
开一家商店,但是如果他们没有登录怎么办?不是吗?
def show
if current_user && current_user.store.blank?
redirect_to new
else
@items = Item.where(store_id: @store.id)
end
end