Reputation: 1276
So I have an email field in a model.
I would like a path in this model, where a field shows up in the view, and when I type an email address, and that address matches an existing model, it gets deleted. For unsubscribing from newsletter.
something like this:
newsletter_controller.rb
def unsubscribe(email)
@newsletter = Newsletter.where(:email => email)
@newsletter.destroy
end
in the view:
simple_form_for @newsletter do |f|
f.input :email, method: delete
end
I got no idea how the view should work in the Rails Way.
Upvotes: 0
Views: 50
Reputation: 13014
In config/routes.rb
, I suppose you have resources :newsletters
Add a route for unsubscribe
as following:
resources :newsletters do
post 'unsubscribe', :on => :member
end
Check rake routes
, you should have obtained a route path as unsubscribe_newsletter_path
with POST verb.
Now, in your view:
=form_for(:newsletter, :url => unsubscribe_newsletter_path) do |f|
=f.label :email
=f.text_field :email
=f.submit "Unsubscribe"
(Change it as per syntax of simple_form)
Now, in newsletter_controller.rb
(it should have been newsletter*s*_controller), add the method as:
def unsubscribe
@newsletter = Newsletter.where(:email => params[:newsletter][:email])
@newsletter.destroy if @newsletter
redirect_to root_path
end
I hope it helps. Comment with places where it gives you error or doesn't work. I'll try to help.
Good luck. :)
Upvotes: 1