Reputation: 10813
In my application, I've a 'warehouse' model that own several fields such as id,name,description, etc, and a boolean field called 'done'.
In my view, I want to insert a button or link field,which, when clicked, should set (through HTTP POST method) warehouse.done = true How can I do this?
Notes: User cannot input warehouse.done field so I suppose to pass it to application as hidden field
Upvotes: 1
Views: 212
Reputation: 6728
Use link to with remote option.
<%= link_to "Vote", {:controller=>"your_controller_name", :action => 'vote',:id=>@warehouse.id, :vote=>true}, :remote=> true, :method => :put %>
In your controller
def vote
@warehouse = Warehouse.find(params[:id])
@warehouse.update_attribute(:vote, params[:vote])
respond_to do |format|
format.js
end
end
In your routes file
resources :your_controller_name do
collection do
put 'vote'
end
end
In your voting view page add new DIV to display flash notice.
<div id="flash_notice" style="display: none;"></div>
Create new RJS template "vote.js.erb" with following code.
$("#flash_notice").html("You have voted successfully");
$("#flash_notice").show("slow");
Let me know if you have any problem.
Upvotes: 3
Reputation: 1876
I made a couple of assumptions on the views, controller.
html
<a href="#" id="set-warehouse-done"> DONE </a>
<input id="warehouse-id" type="hidden" value="24">
js
$(document).ready(function() {
$('#set-warehouse-done').click(function() {
$.ajax({
url: '/warehouse/' + $('#warehouse-id').attr('value');
type: 'POST'
data: done: true
});
});
}
warehouse_controller.rb
def update
@warehouse = Warehouse.find(params[:id])
if params[:done]
if @warehouse.update_attributes(:done, params[:done])
flash[:notice] = 'Warehouse updated successfully'
else
flash[:error] = 'Could not update warehouse'
Upvotes: 1