在Rails中,我应该如何使用ajax更新数据库中的值?

时间:2013-07-25 09:55:45

标签: ruby-on-rails ajax

勾选复选框后,我只想更新数据库中的“需要”值。 脚本列在下面

 $('td div').find('input[type=checkbox]').click(function(){
 $.ajax({
          type: "PUT",
          dataType: "script",
          url: '/ecs/2',
          contentType: 'application/json',
          data: JSON.stringify({ ecs:{needed:'N'}, _method:'put' })
          }).done(function( msg )
          {
          alert( "Data Saved: " + msg );
          });
});

}); 并且控制器的代码是标准的。

# PATCH/PUT /ecs/1
  # PATCH/PUT /ecs/1.json
  def update
    respond_to do |format|
      if @ec.update(ec_params)
        format.html { redirect_to @ec, notice: 'Ec was successfully updated.' }
        format.json { head :no_content }
        format.js
      else
        format.html { render action: 'edit' }
        format.json { render json: @ec.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end

EC是模块的名称,需要的是列的名称。我只是想用id = 2更新ec所需的新值。 但是现在,我总是遇到不好的请求。 我不确定问题出在哪里。

1 个答案:

答案 0 :(得分:0)

为你的复选框(让它不引人注目,这只是一个简单的例子):

... onclick="$.post('/url', {omg_it_is_checked: $(this).attr('checked')})"
routes.rb中的

post '/url' => 'my_controller#my_action'
控制器中的

def my_action
   #....
   @var = some.actions.here.with(params[:omg_it_is_checked]) #or update what you need 
   respond_to do |format|
     format.js{render layout: false}
   end
end

比你必须有一个适当的视图my_action.js.erb,如下所示:

$('#my_uniq_dom_id').html('<%= j render partial: 'new_piece_of_html' %>') #you can render nothing or flash something

最后我们需要的是_new_piece_of_html.html.erb

<div id="new_ajaxed_content"><%= @var %></div> <!-- or you can render checked checkbox, even with animation, or error message if in some reason it was not saved -->

瞧!控制器操作

后,div#my_uniq_dom_id更新为div#new_ajaxed_content

完全不同的方法 - 使用this gem。它是简单解决方案的简单需求

喝彩!