[必備] [JDStore] 讓客戶一眼就知道你在賣什麼

效果說明:

當有人微信推薦你這兩個商品,你會想打開哪一個?

在製作購物網站時非常重要的一個功能

你的「網址」必須讓人一眼看出是在賣什麼

馬上來修改吧!

預計時間: 3分鐘

rails g migration add_friendly_id_to_events

db/migrate/xxxx_add_friendly_id_to_events.rb
 +  def change
 +     add_column :products, :friendly_id, :string
 +     add_index :products, :friendly_id, :unique => true
 +
 +     Product.find_each do |e|
 +       e.update( :friendly_id => SecureRandom.uuid )
 +     end
 +  end

rake db:migrate

app/models/product.rb
 +  validates_presence_of :friendly_id
 +  validates_uniqueness_of :friendly_id
 +  validates_format_of :friendly_id, :with => /\A[a-z0-9\-]+\z/
 +  before_validation :generate_friendly_id, :on => :create
 +
 +  def to_param
 +   self.friendly_id
 +  end
 +
 +  protected
 +
 +  def generate_friendly_id
 +   self.friendly_id ||= SecureRandom.uuid
 +  end

將原本以ID搜尋改為以名稱搜尋

app/controllers/admin/products_controller.rb
def show
 -    @product = Product.find(params[:id])
 +    @product = Product.find_by_friendly_id!(params[:id])

def edit
 -    @product = Product.find(params[:id])
 +    @product = Product.find_by_friendly_id!(params[:id])
 
def update
 -    @product = Product.find(params[:id])
 +    @product = Product.find_by_friendly_id!(params[:id])
 
def destroy
 -    @product = Product.find(params[:id])
 +    @product = Product.find_by_friendly_id!(params[:id])
 
    def product_params
 -    params.require(:product).permit(:title, :description, :price, :quantity, :image)
 +    params.require(:product).permit(:title, :description, :price, :quantity, :image, :friendly_id)
    end

同樣修改以下show destroy add_to_cart
只要有@product = Product.find(params[:id])的地方就換成
@product = Product.find_by_friendly_id!(params[:id])

app/controllers/products_controller.rb
def show
def destroy
def add_to_cart
 -    @product = Product.find(params[:id])
 +    @product = Product.find_by_friendly_id!(params[:id])

新建或修改產品時就可以自己輸入喜歡的網址了
現在朋友在微信上還沒打開就可以知道你給他看的是什麼

大大提高網站的曝光率!

添加Admin輸入網址的欄位

app/views/admin/products/edit.html.erb
 +<div class="form-group">
 +  <%= f.label :friendly_id %>
 +  <%= f.text_field :friendly_id, :required => true, :class => "form-control" %>
 +  <p class="help-block">限小写英数字及横线,将作为网址的一部分</p>
 +</div>
app/views/admin/products/new.html.erb
+<div class="form-group">
 +  <%= f.label :friendly_id %>
 +  <%= f.text_field :friendly_id, :required => true, :class => "form-control" %>
 +  <p class="help-block">限小写英数字及横线,将作为网址的一部分</p>
 +</div>

以上內容是全棧營教程所教,我改為適合JDStore的配置
參考 Rails百寶箱 1



希望您喜歡這篇文章,請抽空幫我投一票,謝謝!



如果获得2等奖,我会从投票给我的VIP学员里抽出1位赠送这本有香气的励志书


comments powered by Disqus