user3450044
user3450044

Reputation: 117

Rails calling a method

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.

Upvotes: 0

Views: 85

Answers (1)

Robin
Robin

Reputation: 21894

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
     }
   })
})

Upvotes: 1

Related Questions