Reputation: 1017
I am trying to get a button_to to call a controller. I've tried a number of variations and nothing seems to work.
In my index.html.erb, I have
<%= button_to "Clear Search", { :controller => 'documents', :action => 'reset_search'} %>
In my documents controller, I have
helper_method :reset_search
def reset_search
@documents = Document.all
$search = nil
params[:search] = nil
redirect_to documents_path
$temp2 = 'testing 1 2 3'
end
On the index, I put the following at the bottom.
$temp2 <%= $temp2 %>
Based on the $temp2 variable, I can see that I am not getting to the reset_search method when clicking the button as the contents of $temp2 are not changing
What do I need to do to actually have the button call the reset_search method?
Upvotes: 0
Views: 21
Reputation: 1017
The problem was that I had my button_to inside the other form tag. I moved it after the <% end %> and it is now working as expected.
<%= form_tag documents_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
<% if $search != '' then %>
<%= button_to "Clear Search", { :controller => 'documents', :action => 'reset_search'} %>
<% end %>
Upvotes: 0
Reputation: 4443
You could use ajax to call the method on click:
$('.whatever-button-class').on('click', function(e){
e.preventDefault();
$.ajax({
type: 'GET',
url: '/documents/reset_search', // make sure you have a route
data: {
// whatever data you want to send as key-value pairs
}
}).done(function(ajax_response){
console.log(ajax_response)
})
})
Inside that controller action:
def reset_search
# whatever you want to do
render :json => {data: "Huzzah!"} # whatever data you want to pass back
end
Upvotes: 1