使用 Rails 3.2 和 Paperclip 保存照片。我正在尝试将用户的 ID 保存到user_id
表photos
中,计数器缓存增量在photos_count
表users
中。被photos
上传到另一个shops
. 照片被上传,但我无法将user
对象传递给photo
模型来创造奇迹。
事情不工作:
- 用户 ID 未能保存在
photos
表user_id
列中 photos_count
每当通过表单上传照片时,inusers
table 都不会增加。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 %>
我试图把它放进去,photo.rb
但它返回user
为零:
after_create :save_associated_user
private
def save_associated_user
self.user_id = self.user
end