我設置了我的Rails應用程序來使用friendly_id和paperclip,並且我已經使用遷移將slug列添加到'designs'數據庫表中。當我創建一個新的設計後,並上傳自己的形象(使用回形針)當我檢查數據庫,然後我得到一個有效記錄的錯誤,說下面沒有更新slug列:Rails活動記錄::沒有找到使用友好的ID和slu recognition識別
這裏有我的代碼片段:
型號:
class Design < ApplicationRecord
attr_accessor :slug
extend FriendlyId
friendly_id :img_name, use: [:slugged, :finders]
has_attached_file :image, styles: {
:thumb => ['100x100#', :jpg, :quality => 70],
:preview => ['480>', :jpg, :quality => 70],
:large => ['800>', :jpg, :quality => 30],
:retina => ['1200>', :jpg, :quality => 30]
},
:convert_options => {
:thumb => '-set colorspace sRGB -strip',
:preview => '-set colorspace sRGB -strip',
:large => '-set colorspace sRGB -strip',
:retina => '-set colorspace sRGB -strip -sharpen 0x0.5'
}
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
控制器:
class DesignsController < ApplicationController
before_action :find_design, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@designs = Design.all.order("created_at desc")
end
def new
@design = Design.new
end
def create
@design = Design.new(design_params)
if @design.save
redirect_to @design, notice: "Hellz yeah, Steve! Your artwork was successfully saved!"
else
render 'new', notice: "Oh no, Steve! I was unable to save your artwork!"
end
end
def show
end
def edit
end
def update
if @design.update design_params
redirect_to @design, notice: "Huzzah! Your artwork was successfully saved!"
else
render 'edit'
end
end
def destroy
@design.destroy
redirect_to designs_path
end
private
def design_params
params.require(:design).permit(:img_name, :slug, :image, :caption)
end
def find_design
@design = Design.friendly.find(params[:id])
end
end
視圖(#show)
<div id="post_show_content" class="skinny_wrapper wrapper_padding">
<header>
<p class="date"><%= @design.created_at.strftime("%A, %b %d") %></p>
<h1><%= @design.img_name %></h1>
<hr>
</header>
<%= image_tag @design.image.url(:retina), class: "image" %>
<div class="caption">
<p><%= @design.caption %></p>
</div>
<% if user_signed_in? %>
<div id="admin_links">
<%= link_to "Edit Artwork", edit_design_path(@design) %>
<%= link_to "Delete Artwork", design_path(@design), method: :delete, data: {confirm: "Are you sure?" } %>
</div>
<% end %>
</div>
遷移:
class AddSlugToDesigns < ActiveRecord::Migration[5.0]
def change
add_column :designs, :slug, :string
add_index :designs, :slug, unique: true
end
end
不確定about的friendly_id,但你可以使用activerecord find_by'Design.find_by(slug:params [:id])'讓它工作 – sa77
歡呼聲 - 對不起,我將那個文件添加到? – sdawes
用'@design = Design.find_by(slug:params [:id])在你的控制器上用你的find_design動作替換它' – sa77