如何返回最近创建的元素的id - Ruby on Rails?

时间:2014-08-16 20:55:00

标签: ruby-on-rails ruby ajax response

我必须插入并使用id来插入另一个东西。

我想做这样的事情

var id_team;
$.ajax({
    url:    "/teams",
    type:   "POST",
    data:   {"authenticity_token": tokentag, team:{name:team, champeonship_id:champ}},
    success: function(response){
        id_team = response.id;
            alert(id_team);
        for(var i=1; i<14; i++){
            var rut = $('#rut'+i).val();
            var nom = $('#nom'+i).val();

            $.ajax({
              url:    "/players",
              type:   "POST",
              data:   {"authenticity_token": tokentag, player:{rut:rut, num:i, name:nom, team_id:id_team, champeonship_id:champ}},
              success: function(response){
                if(response.num==13){
                    alert('Saved');
                    window.location.assign("/create_team");
                }
              }
            });
        }
    }
});

动作:

# POST /teams
# POST /teams.json
def create
  @team = Team.new(team_params)

  respond_to do |format|
    if @team.save
      format.html { redirect_to @team, notice: 'Team was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end

response.id现在未定义,我该怎么办? 我将变量声明为外部并继续未定义

2 个答案:

答案 0 :(得分:0)

您可以在控制器中创建您的创建操作,以使用创建的团队的ID发送json对象。并使用dataType:&#39; json&#39;

制作ajax帖子

编辑:

# POST /teams
# POST /teams.json
def create
  @team = Team.new(team_params)

  respond_to do |format|
    if @team.save
      format.html { redirect_to @team, notice: 'Team was successfully created.' }
      format.json { render json: { team_id: @team.id} }
    else
      format.html { render action: "new" }
    end
  end
end

答案 1 :(得分:0)

亚历克斯的评论是正确的。您想使用model callback并将该逻辑保留在控制器之外(Fat Model,Skinny Controller是rails惯用语)。它看起来像这样:

MyModel.rb
  after_create :create_team

  private
    def create_team
      # the logic you're trying to perform with that second ajax call belongs here
    end
end

作为第二个问题,您错过了控制器中的format.js块。没有它,您的控制器不知道如何处理您发送它的AJAX POSTThe docs为此提供了使用javascript的好例子。