Last active
December 10, 2015 14:08
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.... | |
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 | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Lead < ActiveRecord::Base | |
attr_accessible :email | |
has_one :referral | |
has_one :user, :through => :referrals | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Referral < ActiveRecord::Base | |
attr_accessible :lead_id, :user_id | |
belongs_to :user | |
belongs_to :lead | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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