Reputation:
Here is my method in my user controller:
def donation_custom(amount)
@user = current_user
@user.amount_donated += amount
@user.save
redirect_to root_path, :alert => "thanks for donating"
end
I just need a simple input form in my view so i can call this method and pass the user input to my "amount" argument.
thanks in advance!
Upvotes: 0
Views: 81
Reputation: 82
Why not just stick with the RESTful way of doing this? Create a custom setter method in your User model:
validates :add_amount, numericality: {greater_than_or_equal_to: 0}
def add_amount=(value)
self.amount_donated += value
end
then create a simple form that captures this:
<%= form_for @user do |f| %>
Amount to donate <%= f.text_field :add_amount %><br>
<%= f.submit "Donate!" %>
<% end %>
and then use your UsersController#update
method to set this:
def update
@user = User.find(params[:id])
# you'll probably want to add some error checking here
@user.update_attributes(user_params)
redirect_to root_path, notice: "Thanks for donating!"
end
private
def user_params
# you'll probably want to whitelist other parameters here
params.require(:user).permit(:add_amount)
end
Upvotes: 1
Reputation: 27961
I'm not recommending this as a general approach to this problem, and there are other issues in your code that I'm not pointing out, but your request is so specific that you're obviously just looking for a specific solution to this problem, so...
Remove the args from the method signature, all form parameters are presented to controllers as a hash called params
, so your method should become:
def donation_custom
@user = current_user
@user.amount_donated += params[:amount]
@user.save
redirect_to root_path, :alert => "thanks for donating"
end
And then in your view you will have something like this:
<%= form_tag '/your_controller/donation_custom' do -%>
<div><%= text_field_tag :amount %></div>
<div><%= submit_tag 'Save' %></div>
<% end -%>
Upvotes: 1
Reputation: 64
The form_for helper accepts a parameter called url and here you should use the route helper of that controller donate_custom_path and then instead of doing
@user.amount_donated = amount
You do
@user.amount_donated = params[:amount]
And you leave the donation_custom with 0 parameters
Upvotes: 0