0

Rails 3.2 と Paperclip を使用して写真を保存します。ユーザーのIDをテーブルに保存しようとしていuser_idます.テーブルphotosのカウンタキャッシュの増分photos_countですusers。は別のphotosにアップロードされshopsます。写真はアップロードされますが、userオブジェクトをphotoモデルに渡して奇跡を起こすことはできません。

うまくいかないこと:

  1. photosユーザー ID が表のuser_id列に保存されない
  2. 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
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 に答える