0

我有两个模型:照片和产品。这些通过 has_many 关联并嵌套在其中。

在我的产品控制器中的“创建”操作中,我将用户上传的所有未链接到产品的照片关联起来。(我这样做是因为照片是通过 ajax 添加的)。

现在在编辑页面上。我想添加照片。这需要我将照片链接到产品。在我在创建操作中这样做之前。但正如您在 Rails 中所知道的那样,没有真正的编辑操作。因此,我的产品控制器中没有任何地方我加入了两者。

那么,我该如何解决呢?

PS在你问之前我不能在照片控制器中加入两者

产品控制器

  def new 
    Photo.where(:product_id => nil, :user_id => current_user).delete_all
    @product = Product.new
    @photo = Photo.new
  end

  def create
  binding.pry
  @product = current_user.products.create(params[:product])
    if @product.save
      Photo.where(:product_id => nil, :user_id => current_user).update_all(:product_id => @product.id) 
      render "show", notice: "Product created!"
    else
      render "new", error: "Error submitting product"
    end
  end

  def edit
    @product = Product.find(params[:id])
    @photo = Photo.new
  end

照片控制器

  def create
  @photo = Photo.new(params[:photo])
    respond_to do |format|
      @photo.user_id = current_user.id
      if @photo.save
        format.html {
          render :json => [@photo.to_jq_image].to_json,
          :content_type => 'text/html',
          :layout => false
        }
        format.json { render json: {files: [@photo.to_jq_image]}, status: :created, location: @photo }
      else
        format.html { render action: "new" }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end
4

2 回答 2

2

有一种方法

def update
end 

存在

于 2013-07-16T08:24:50.257 回答
0

如果您至少使用一次脚手架来观察典型的 Rails 控制器,这可能会有所帮助。我会注意生成的方法。

于 2013-07-16T05:48:00.930 回答