2012-01-14 79 views
2

获取PARAMS我所以在这个动作我创建了一个新的“项目”,我想达到什么创造了一个新的动作在这样从Ajax响应的Rails

def newitem 
    @Item = Item.new(:description => params[:description], :type_id => params[:type]) 
    if @Item.save 
    #Magic supposed to happen here 
    end 
    end 

的“贡献”控制器是让在AJAX响应中创建的项目的ID,所以我可以在创建“项目”的相同视图中使用它...

第一个问题,我如何从控制器发回已创建项目的参数? 第二我知道如何处理Ajax请求,但我如何处理对第一个请求的Ajax响应...

也许我在思考解决方案,但不知道如何去做。 在此先感谢。

回答

1

有几种方法可以解决这个问题。该方法如下解释是为Rails 3.1

呼叫在你的方法直接呈现(这种做法是一个JSON API唯一的方法帮助的,因为HTML渲染将是不存在的。):

def newItem 
    @Item = Item.create(:description => params[:description], :type_id => params[:type]) 
    render json: @Item 
end 

使用respond_do块:

def newItem 
    @Item = Item.create(:description => params[:description], :type_id => params[:type]) 

    respond_to do |format| 
    if @Item.save 
     format.html { redirect_to @Item, notice: 'Item was successfully created.' } 
     format.json { render json: @Item, status: :created, location: @Item 
    else 
     format.html { render action: "new" } 
     format.json { render json: @Item.errors, status: :unprocessable_entity } 
    end 
    end 
end 

教你的控制器的响应格式,你的愿望:

class ContributionsController < ApplicationController 
    # Set response format json 
    respond_to :json 

    ... 

    def newItem 
    @Item = Item.create(:description => params[:description], :type_id => params[:type]) 
    respond_with @Item #=> /views/contributions/new_item.json.erb 
    end 

可能的“疑难杂症” ......

如果验证失败的项目创建,你不会得到的ID后面,也不会报告故障(比HTTP响应代码等)

添加以下你的模型。它将在json响应中包含验证失败的错误哈希值

class Item < ActiveRecord::Base 

    ... 

    # includes any validation errors in serializable responses 
    def serializable_hash(options = {}) 
    options = { :methods => [:errors] }.merge(options ||= {}) 
    super options 
    end 

永远有不止一种方式来为猫皮肤。我希望这可以帮助