weixin_33747129 2014-04-06 01:10 采纳率: 0%
浏览 10

Rails调用方法

I am a new user of rails and web languages in general and I am trying to understand the method calling functioning. A method in my controller:

def azer
 @usr=User.all
 @test = User.first
 def incr()
  @test.nbr_set = @test.nbr_set+1
  @test.save
 end
 incr()
end

The route : get "test/azer"

azer.html.erb :

<%= @test.username %></br>
<%= @test.nbr_set %></br>

When I refresh the page, nbr_set is increasing but I don't want to do that with this way.

In a first time, how can I define a route that will call my incr() method? Because now, the incr() method is automatically called and it's a problem.

Then, is it possible to make an ajax button who will increase nbr_set without refreshing the page? How can i make it?

Finally, I am trying to learn ajax with ruby but it's difficult and I don't understand how I can load a html.erb file who while update my database without refreshing my page.

  • 写回答

1条回答 默认 最新

  • weixin_33724046 2014-04-06 01:36
    关注

    First of all, the incr method will be redefined every time you call azer, because Ruby doesn't support nested methods per se.

    To increment the count on a user, you would do:

    # routes.rb
    resources :users do
        member do
           put :increment_nbr
        end
    end
    
    # users_controller
    respond_to :html, :json
    def increment_nbr
        @user = User.find(params[:id])
        @user.increment! :nbr_set
        render json: { nbr: @user.nbr_set }.to_json
    end
    
    # html
    <%= @user.nbr_set %>
    <%= link_to "Increment", increment_nbr_user_path(@user), data-increment %>
    
    # js
    $("[data-increment]").on("click", function(e) {
       e.preventDefault()
       $link = $(this)
       $.ajax({
         url: $link.attr("href"),
         dataType: "json",
         type: "PUT",
         success: function(data) {
           # data.nbr will be your new count
           # figure out a way to update the value in the dom here
         }
       })
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图
  • ¥15 智能除草机器人方案设计
  • ¥15 对接wps协作接口实现消息发送
  • ¥15 SQLite 出现“Database is locked” 如何解决?