iveはfriendly_idとpaperclipを使用するように私のレールアプリを設定して、移行を使用して 'デザイン'データベーステーブルにスラグカラムを追加しました。私は、新しいデザインのポストを作成し、(ペーパークリップを使用して)私の画像をアップロードすると、私はデータベースをチェックして、私は次のように言って、アクティブなレコードのエラーを取得する際にslugカラムは更新されません。Railsのアクティブレコード::フレンドリーなIDとスラッグの認識
をここにあります私のコードスニペット:
モデル:
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
フレンドリーIDについてはわかりませんが、activerecord find_by 'Design.find_by(slug:params [:id])を使用して動作させることができます。 – sa77
歓声 - どのファイルに追加しますか? – sdawes
コントローラーのfind_designアクションの代わりに '@design = Design.find_by(slug:params [:id]) 'を入力してください – sa77