使用Rails 3.2和Paperclip保存照片。我正在尝试将用户的ID保存到user_id
表中的photos
,photos_count
表users
中的计数器缓存增量。 photos
已在另一个shops
上传。照片上传了,但我无法将user
对象传递给photo
模型以实现其奇迹。
事情不起作用:
photos
表user_id
列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 %>
我尝试将其放入photo.rb
,但返回user
为零:
after_create :save_associated_user
private
def save_associated_user
self.user_id = self.user
end
答案 0 :(得分:0)
您需要attr_accessible user_id,而非用户。
答案 1 :(得分: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 %>
提交后,您需要调用一些回调来更新用户表中的photos_count