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 に答える