ajaxruby-on-rails-3jquerylink-to-remote

Using link_to remote: true to pass parameters to rails


So I have a page with several messages, each with a link that changes (refines) the RATING of that message. When a user clicks on this link, I want an AJAX call that updates the corresponding column value in the database for that message. When this link is clicked, nothing should happen visibly. There should be no page refresh or reload.

I've been trying to do this using link_to remote: true, but I can't seem to get it to work. Documentation online is fairly unclear on this question and with the changes between Rails 2 and 3, some things like :with are no longer supported.

I've copied what I have so far, but I know its far from even coming close to a solution. In terms of parameters I need passed into the database, I need the profile_id, the message_id and the new_rating.

Thanks in advance!

show.html.haml

.status-bar
  = link_to "", { action: :refine_result }, remote: true

profile_controller.rb

...

def refine_result
  @refinement = ResultRefinement.new
  @refinement.profile_id = params[:profile_id]
  @refinement.message_id = params[:message_id]

  @refinement.save

  respond_to do |format|
    format.html { render nothing: true }
    format.js { render nothing: true }
  end
end

result_refinement.rb

class ResultRefinement < ActiveRecord::Base
  attr_accessible :profile_id, :message_id, :new_rating, :deleted

  belongs_to :profile
end

Solution

  • You need to set up a route for ProfileController#refine_result first. Something like

    match '/profile/refine_results' => 'profile#refine_results', :as => 'refine_results'
    

    Then you can use

    .status-bar
      = link_to "", refine_results_url(profile_id: 1, message_id: 100, new_rating: "awful"), remote: true