0

使用 Rails 3.2 和 Paperclip 保存照片。我正在尝试将用户的 ID 保存到user_idphotos中,计数器缓存增量在photos_countusers中。被photos上传到另一个shops. 照片被上传,但我无法将user对象传递给photo模型来创造奇迹。

事情不工作:

  1. 用户 ID 未能保存在photosuser_id列中
  2. photos_count每当通过表单上传照片时,in userstable 都不会增加。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
4

2 回答 2

0

您需要 attr_accessible user_id,而不是用户。

于 2012-11-13T15:22:46.270 回答
0

在表单中,您必须在 photos_attributes 中设置 user_id,如下所示,

<%= 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 %>

提交后,您需要调用一些回调来更新 users 表中的 photos_count

于 2012-11-13T15:43:15.783 回答