[英]Polymorphic Association in Ruby on Rails
我的嘗試是為與Photos
關聯的模型Items
和Venues
創建多態關聯。 我最初使用了Rails最佳實踐-如何設計用於多次上傳的模型? 但有一些錯誤,這是到目前為止的代碼:
class Item < ActiveRecord::Base
has_many :photos, :as => :assetable, :class_name => "Item::Photo", :dependent => :destroy
accepts_nested_attributes_for :photos
class Venue < ActiveRecord::Base
has_many :photos, :as => :assetable, :class_name => "Photo", :dependent => :destroy
accepts_nested_attributes_for :photos
class Photo < ActiveRecord::Base
belongs_to :asset
end
class Asset < ActiveRecord::Base
has_many :photos
belongs_to :assetable, :polymorphic => true
delegate :url, :to => :attachment
end
class Venue::Photo < Asset
has_attached_file :attachment,
:styles => {
:large => "640x480",
:medium => "300x300",
:thumb => "100x100"
},
:path => "/:style/:id/:filename"
end
class Item::Photo < Asset
has_attached_file :attachment,
:styles => {
:large => "640x480",
:medium => "300xa300",
:thumb => "100x100"
},
:path => "/:style/:id/:filename"
class VenuesController < ApplicationController
# GET /venues
# GET /venues.json
def index
#@venues = Venue.all
params[:page] ||= 1
@venues = Venue.paginate(:page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @venues }
end
end
# GET /venues/1
# GET /venues/1.json
def show
@venue = Venue.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @venue }
end
end
# GET /venues/new
# GET /venues/new.json
def new
@venue = Venue.new
5.times do
@venue.assets.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: @venue }
end
end
# GET /venues/1/edit
def edit
@venue = Venue.find(params[:id])
5.times { @venue.assets.build }
end
# POST /venues
# POST /venues.json
def create
@venue = Venue.new(params[:venue])
#@venue.tag_list ="asian, chinese"
respond_to do |format|
if @venue.save
format.html { redirect_to @venue, notice: 'Venue was successfully created.' }
format.json { render json: @venue, status: :created, location: @venue }
else
format.html { render action: "new" }
format.json { render json: @venue.errors, status: :unprocessable_entity }
end
end
end
# PUT /venues/1
# PUT /venues/1.json
def update
@venue = Venue.find(params[:id])
respond_to do |format|
if @venue.update_attributes(params[:venue])
format.html { redirect_to @venue, notice: 'Venue was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @venue.errors, status: :unprocessable_entity }
end
end
end
# DELETE /venues/1
# DELETE /venues/1.json
def destroy
@venue = Venue.find(params[:id])
@venue.destroy
respond_to do |format|
format.html { redirect_to venues_url }
format.json { head :no_content }
end
end
end
錯誤消息,當我嘗試編輯場所時收到錯誤消息“未知屬性:assetable_id”,而當我嘗試編輯項目時收到錯誤消息“ nil:NilClass的未定義方法”照片”
您是否按照指南所示設置了數據庫?
為什么要定義模型photo
和has_many :photos
?
如果您的照片樣式相同,則無需STI。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.