Using link_to remote: true to pass parameters to rails
Asked Answered
R

1

6

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
Rosa answered 10/7, 2012 at 19:55 Comment(0)
H
7

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
Hoggish answered 10/7, 2012 at 22:30 Comment(2)
Awesome. I got it to start passing the parameters and saving them into the database. The only issue I'm still having is stopping the page from redirecting or changing.Rosa
It seems that another js file was overwriting the ajax. Which is why I kept following the link rather than having ajax take over.Rosa

© 2022 - 2024 — McMap. All rights reserved.