使用Rails 3.2和Paperclip保存照片。我試圖將用戶的ID保存在user_id
,photos
表中,計數器緩存增量爲photos_count
的users
表。 photos
上傳到另一個shops
。照片會上傳,但我無法將user
對象傳遞給photo
模型以創造奇蹟。將用戶對象從一個模型傳遞到另一個模型
事情不工作:
- 用戶ID不能被保存在
photos
表user_id
列每當照片通過shops
形式上傳 在
photos_count
users
表沒有得到增加。
下面是我的代碼:
# 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
錯字,對不起。它仍然不起作用。 – Victor
而你的代碼恰恰在你設置照片的user_id?你期望它只是*神奇地*從無處設置? – mrbrdo
請參閱更新的問題。我在'photo'模型中添加了'after_create'。 – Victor