关联的user_id保存在更新操作中,但不存储在create操作中

时间:2013-01-27 02:45:59

标签: ruby-on-rails ruby paperclip

使用Rails 3.2。我update中的shops_controller.rb操作效果很好,相应地保存了user_id,但在create操作中,user_id没有得到保存。我做错了什么?以下是我的代码:

# 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
  has_many :photos, :as => :attachable, :dependent => :destroy

  accepts_nested_attributes_for :photos
end

# user.rb
class User < ActiveRecord::Base
  has_many :photos, :as => :attachable, :dependent => :destroy
end

# shops_controller.rb
class ShopsController < ApplicationController
  before_filter :require_user, :only => [:new, :edit, :update, :create]

  def update
    @shop = Shop.find(params[:id], :include => [:photos => :user])
    ...

    photos = params[:shop][:photos_attributes]
    if !photos.blank?
      photos.each do |photo|
        photo.merge!(:user_id => current_user.id)
      end
    end

    if @shop.update_attributes(params[:shop])
      redirect_to shop_path(@shop)
    else
      render :action => :edit
    end
  end

  def create
    @shop = Shop.new(params[:shop])
    ...

    photos = params[:shop][:photos_attributes]
    if !photos.blank?
      photos.each do |photo|
        photo.merge!(:user_id => current_user.id)
      end
    end

    if @shop.save
      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 %>
  <h3>Pictures</h3>
  <%= f.file_field :shop_photos_data, :multiple => true, :name => "shop[photos_attributes][][data]", :accept => "image/*" %><br>
<% end %>

1 个答案:

答案 0 :(得分:0)

添加一个带有collection_select的用户字段,或者更好地使用config / routes.rb中的嵌套资源,然后在视图中使用form_for[@spot, @user]