2012-11-13 57 views
0

使用Rails 3.2和Paperclip保存照片。我試圖將用戶的ID保存在user_id,photos表中,計數器緩存增量爲photos_countusers表。 photos上傳到另一個shops。照片會上傳,但我無法將user對象傳遞給photo模型以創造奇蹟。將用戶對象從一個模型傳遞到另一個模型

事情不工作:

  1. 用戶ID不能被保存在photosuser_id列每當照片通過shops形式上傳
  2. photos_countusers表沒有得到增加。

下面是我的代碼:

# 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 

回答

0

您需要attr_accessible USER_ID,而不是用戶。

+0

錯字,對不起。它仍然不起作用。 – Victor

+0

而你的代碼恰恰在你設置照片的user_id?你期望它只是*神奇地*從無處設置? – mrbrdo

+0

請參閱更新的問題。我在'photo'模型中添加了'after_create'。 – Victor

0

在你必須設置USER_ID在photos_attributes,像這樣的形式,

<%= form_for @shop, :url => { :action => action, :type => type }, :html => { :mult ipart => true } do |f| %> 
    <%= f.text_field :name %> 
    <%= f.file_field :shop_photos_data, :multiple => true, :name => "shop[photos_attributes][][data]" %> 
    <%= f.hidden_field :shop_photos_user_id, :value => current_user.id, :multiple => true, :name => "shop[photos_attributes][][user_id]" %> 
<% end %> 

提交後,你需要調用一些回調在用戶表更新PHOTOS_COUNT

+0

只有最後一個'user_id'得到保存,其餘未保存。 – Victor

相關問題