我有两个模型Company
和User
公司has_many :users
和用户belongs_to :company
。我的表格如下:
<%= form_for @company, data: {toggle: :validator}, novalidate: "novalidate", html: {role: :form} do |f| %>
公司领域
然后在那里我有
<%= f.fields_for :users, @company.users.build do |user_form| %>
一堆用户字段
它使用users_attributes: {"0" => {name: "Chad"}}
但它不会仅为用户创建公司对象。
公司模式
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
用户模型
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