将用户对象从一个模型传递到另一个模型

时间:2012-11-13 15:16:36

标签: ruby-on-rails paperclip

使用Rails 3.2和Paperclip保存照片。我正在尝试将用户的ID保存到user_id表中的photosphotos_countusers中的计数器缓存增量。 photos已在另一个shops上传。照片上传了,但我无法将user对象传递给photo模型以实现其奇迹。

事情不起作用:

  1. 用户ID无法保存在photosuser_id
  2. 中 每当通过photos_count表单上传照片时,users表格中的
  3. shops都不会增加。
  4. 以下是我的代码:

    # 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
    

2 个答案:

答案 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