0

How can I in Rails write a Coffeescript function to update a database column? I guess an Ajax call of sorts would be ideal:

id = $('#document').attr('data-document-id')
$.ajax
  url: "/documents/#{id}/update_attr"
  type: "GET"
  success: (data) ->
    console.log(data)

Is something like this the only way? Or is there something better?

1 Answer 1

2

Well, keep in mind that frontend code (html, css, js) cannot access the database directly. So you need an AJAX request.

REST best practices would require you to use a POST/PUT/PATCH method instead of the GET method which should never change the state of the application.

Also, you are not passing any value to the Rails backend.

$.ajax
   url: "/whatever/#{id}"
   type 'POST'
   data:
     key: value
   success: (data)->
     console.log data

On the Rails side you need to setup the appropriate route in config/routes.rb:

post '/whatever/:id', to: 'some_controller#some_action'

Still ideally, following the best practices, you probably have some sort of

resources :apples

already mapped to an ApplesController. You now have to implement the action, which will be like this:

def update
  @object = Whatever.find(params[:id])
  if @object.update(key: params[:key]
    render json: { success: 1 }
  else
    render json: { success: 0 }
  end
end

That implementation is not complete (it does not handle HTML requests, multi-key updates and other fancy things), but still it should solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.