我刚开始用ruby编写代码,所以这是初学者的疑问。我在一个市场应用程序工作。我试图在我的卖家秀中创建一个条件,这取决于用户是否是卖家,但它不起作用。
我的型号中有这样的配置:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :sellers
has_many :products, through: :sellers
has_many :orders
has_many :reviews
end
class Seller < ApplicationRecord
belongs_to :user
has_many :orders
has_many :reviews, through: :orders
has_many :products
end
class Product < ApplicationRecord
belongs_to :seller
end
class Order < ApplicationRecord
belongs_to :user
belongs_to :seller
has_many :reviews
end
class Review < ApplicationRecord
belongs_to :user
belongs_to :order
end
这是我的卖家管理员:
class SellersController < ApplicationController
def index
@sellers = Seller.all
end
def show
@seller = Seller.find(params[:id])
end
def new
@user = current_user
@seller = Seller.new
end
def create
@user = current_user
@seller = Seller.new(seller_params)
@seller.user = @user
if @seller.save
redirect_to seller_path(@seller.id), notice: 'Sua loja foi criada com sucesso!'
else
render :new
end
end
def edit
end
private
def seller_params
params.require(:seller).permit(:seller_name, :category)
end
end
Bellow,我的产品管理员:
class ProductsController < ApplicationController
def index
@products = Product.all
end
def show
@product = Product.find(params[:id])
end
def new
@seller = current_user.seller
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
redirect_to product_path(@product.id), notice: 'Novo produto criado com sucesso!'
else
render :new
end
end
def edit
end
private
def product_params
params.require(:product).permit(:product_name, :product_description, :product_size, :product_price)
end
end
我正试图把卖家的节目编码成这样,但它不起作用:
<h1>Seller details</h1>
<h3> <%= @seller.seller_name %> </h3>
<p> <%= @seller.category %> </p>
<% if current_user.seller %>
<%= link_to "Create new product", new_product_path(@product), class: 'btn btn-primary' %> %>
<% else %>
<%= @products.each do |product| %>
<h4> <%= product.product_name %> </h4>
<p> <%= product.product_description %> </p>
<p> <%= product.product_size %> </p>
<h6> <%= product.product_price %> </h6>
<% end %>
<% end %>
如果用户是卖家,我如何应用此条件?Tks
如果用户有一个卖家,您应该设置为:
class User < ApplicationRecord
has_one :seller
end