Skip to content

Instantly share code, notes, and snippets.

@patrickcurl
Last active December 10, 2015 14:08
Show Gist options
  • Save patrickcurl/4446081 to your computer and use it in GitHub Desktop.
Save patrickcurl/4446081 to your computer and use it in GitHub Desktop.
Rails associations and create method question... How do I create a new lead for user_id: 1 --and at the same time create the referral association?
....
def create
@lead = Lead.new(email: params[:user][:email], user_id: 1)
respond_to do |format|
if @lead.save
format.html { redirect_to @lead, notice: 'User was successfully created.' }
format.json { render json: @lead, status: :created, location: @lead }
else
format.html { render "new" }
format.json { render json: @lead.errors, status: :unprocessable_entity }
end
end
end
...
class Lead < ActiveRecord::Base
attr_accessible :email
has_one :referral
has_one :user, :through => :referrals
end
class Referral < ActiveRecord::Base
attr_accessible :lead_id, :user_id
belongs_to :user
belongs_to :lead
end
class User < ActiveRecord::Base
has_secure_password
has_many :referrals
has_many :leads, :through => :referrals
attr_accessible :address, :city, :email, :first_name, :last_name, :phone, :state, :zip, :password, :password_confirmation, :slug, :referred_by
validates_uniqueness_of :email
validates_presence_of :email
validates_presence_of :password
def name
[first_name, last_name].join " "
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment