0

使用 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 %>
4

1 回答 1

0

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

于 2013-01-27T02:55:52.627 回答