Created nested model setting a property on nested model before save
- by CWitty
I have two models a Company and a User the Company has_many :users and the User belongs_to :company. I have a form such as:
<%= form_for @company, data: {toggle: :validator}, novalidate: "novalidate", html: {role: :form} do |f| %>
company fields
Then in there I have
<%= f.fields_for :users, @company.users.build do |user_form| %>
A bunch of user fields
It posts the data with the nested attributes of users_attributes: {"0" => {name: "Chad"}}
But it doesn't create the user only the company object.
Company Model
class Company < ActiveRecord::Base
has_many :users, dependent: :destroy
has_many :contacts, dependent: :destroy
accepts_nested_attributes_for :users
accepts_nested_attributes_for :contacts
attr_accessor :card_token, :users_attributes
before_create :create_company_customer_token
before_create :create_admin_user
before_destroy :set_deleted_flag
validates_presence_of :name, :phone_number
private
def create_admin_user
self.users.first.admin = true
end
def set_deleted_flag
self.deleted = true
save
users.each do |u|
u.destroy
end
false
end
def create_company_customer_token
begin
customer = Stripe::Customer.create(description: "Company: #{self.name}", card: self.card_token, plan: self.plan)
self.stripe_customer_id = customer['id']
rescue Stripe::StripeError => e
self.errors.add(:stripe_customer_id, "Looks like we are having an issue at the moment, please try again shortly")
@logger ||= Rails.logger
@logger.error(e)
end
end
end
User Model
class User < ActiveRecord::Base
include Clearance::User
has_many :messages
belongs_to :company
before_destroy :set_deleted_flag
after_create :send_welcome_email
validates_presence_of :first_name, :last_name
validates_uniqueness_of :email, scope: :company_id, conditions: -> { where.not(deleted: true) }
def name
"#{first_name} #{last_name}"
end
private
def set_deleted_flag
self.deleted = true
save
end
def send_welcome_email
UserMailer.welcome_email(self).deliver
end
end