Reputation: 440
I'm completely new to Ruby, and I've been banging my head on what should be a stupidly easy problem for a while.
I'm starting off with a simple blog application (the one from the Ruby on Rails documentation), and I'm trying to augment it so that users can email posts. I have an email method in the post class working just fine, I'm just having a hard time calling it when a user clicks a link/button.
I realize that this isn't JavaScript and I can't just use an onclick. Perhaps one idea is to route to a link like blog/posts/2/email, but I don't even know where to start with that, and I wouldn't be surprised if there was a simpler approach.
Can someone please help a noob out?
Upvotes: 0
Views: 236
Reputation: 5774
Following code will send mail at post creation. If you want to tie it up with a separate button ("email me") you can move the code in create action to a new action (send_mail) and tie "email me" and "send_mail"
app/controllers/posts_controller.rb
def create
post = Post.new(params[:post])
Mailer.post_it(post).deliver
end
app/mailers/mailer.rb
class Mailer < ActionMailer::Base
default :from => "[email protected]"
def post_it(post)
@post = post
mail(:to => "[email protected]",
:subject => "New Post: #{@post.title}",
:cc => "[email protected]")
end
end
app/views/mailer/post_it.erb
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<p><%= @post.content %></p>
</body>
</html>
Upvotes: 0
Reputation: 17480
Create a controller action for the email delivery
def email_post
@post = Post.find(params[:id])
@post.send_to(params[:email]) #send to is instance method on the model
#assumes email address is being put in a form of some kind
end
Then create a route for the new controller method in routes.rb
resources :posts do
member do
post 'email_post'
end
end
Finally make the form in your view and link it up to your controller action.
Upvotes: 3