Rails 3.2 と Paperclip を使用して写真を保存します。ユーザーのIDをテーブルに保存しようとしていuser_id
ます.テーブルphotos
のカウンタキャッシュの増分photos_count
ですusers
。は別のphotos
にアップロードされshops
ます。写真はアップロードされますが、user
オブジェクトをphoto
モデルに渡して奇跡を起こすことはできません。
うまくいかないこと:
photos
ユーザー ID が表のuser_id
列に保存されないphotos_count
写真がフォーム経由でアップロードされるたびに、users
テーブル内の値が増加しません。shops
以下は私のコードです:
# photo.rb
class Photo < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true, :counter_cache => true
belongs_to :user, :counter_cache => true
attr_accessible :data, :attachable_id, :attachable_type, :user_id
end
# shop.rb
class Shop < ActiveRecord::Base
attr_protected :reviews_count, :rating_average, :photos_count
has_many :photos, :as => :attachable, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
end
# photos_controller.rb
class PhotosController < ApplicationController
end
# shops_controller.rb
class ShopsController < ApplicationController
before_filter :require_user, :only => [:new, :edit, :update, :create]
def new
@shop = Shop.new
end
def edit
@shop = Shop.find(params[:id])
end
def update
@shop = Shop.find(params[:id])
if @shop.update_attributes(params[:shop])
flash[:notice] = 'Successfully updated.'
redirect_to shop_path(@shop)
else
render :action => :edit
end
end
def create
@shop = Shop.new(params[:shop])
if @shop.save
flash[:notice] = 'Successfully saved.'
redirect_to shop_path(@shop)
else
render :action => :new
end
end
end
# shops/_form.html.erb
<%= form_for @shop, :url => { :action => action, :type => type }, :html => { :multipart => true } do |f| %>
<%= f.text_field :name %>
<%= f.file_field :shop_photos_data, :multiple => true, :name => "shop[photos_attributes][][data]" %>
<% end %>
これをに入れようとしましたが、 nilphoto.rb
が返されます:user
after_create :save_associated_user
private
def save_associated_user
self.user_id = self.user
end