Reputation: 1829
I have seen this question asked a lot with people seeking help with creating a newsletter system.
I have a newsletter mailer setup with the use of roadie gem. I need help with figuring out how to setup the subscriber part of the newsletter. I have been doing the newsletters by hand from a mail client so I have around 300 subscribers.
Can someone help me setup the code so that all registered users would automatically be subscribed to the newsletter and I can import my 300 email subscribers to the list. There should be a unsubscribe link also. Assistance would be extremely helpful to me and so many other people out there.
newsletter_mailer.rb:
class NewsletterMailer < ActionMailer::Base
default from: "[email protected]"
def weekly(email)
@newsletter = newsletter
@recipient = recipient
mail to: email, subject: "New Dates Weekly"
end
Newsletter Controller:
def send
@newsletter = Newsletter.find(:params['id'])
@recipients = Recipient.all
@recipients.each do |recipient|
Newsletter.newsletter_email(recipient, @newsletter).deliver
end
end
Users controller:
def settings
@user = User.find(params[:id])
end
def new
@user = User.new
end
def profile
@profile = User.profile
@user = User.find(params[:id])
end
def create
@user = User.new(user_params)
if @user.save
UserMailer.registration_confirmation(@user).deliver
session[:user_id] = @user.id
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
Upvotes: 4
Views: 519
Reputation: 905
It sounds like you need a one-to-one relation between User
and Recipient
:
class User < ActiveRecord::Base
has_one :recipient
...
end
class Recipient < ActiveRecord::Base
belongs_to :user
...
end
Then in your signup process, you just need to create the user's recipient:
def create
@user = User.new(user_params)
if @user.save
...
@user.create_recipient(:email => @user.email)
...
else
render "new"
end
end
See http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one for more details on has_one
methods like create_association
.
Upvotes: 2
Reputation: 8648
This is the classical many-to-many
relationship.
In Rails
it is realized by has_and_belongs_to_many
often refered to as habtm
.
A good start to learn about relationships are the RubyOnRail-Guides
Basicly you need a Newsletter
model and a Subscriber
model and a table newsletters_subscribers
.
class Newsletter < ActiveRecord::Base
has_and_belongs_to_many :subscribers
end
class Subscriber < ActiveRecord::Base
has_and_belongs_to_many :newsletters
end
Upvotes: 0