我有兩個模型,用戶和公司。我已經使用用戶模型創建的設備gem。Rails 5在子創建時生成父記錄,只有在不存在的情況下
class User < ApplicationRecord
belongs_to :company
accepts_nested_attribute_for :company
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
end
class Company < ApplicationRecord
has_many :users
end
當我創建的用戶,我想與他們交往,他們在工作的公司。我已經包含在用戶創建形式COMPANY_NAME屬性。我不想要的是公司表具有同一個company_name屬性的多個記錄。
<% form_for(@user) do |user_form| %>
<% user_form.fields_for :company do |company_form| %>
<%= company_form.label :company_name %>
<%= company_form.text_field :company_name %>
<% end %>
# other fields for user
<% end %>
我想檢查用戶是否與公司關聯,已經存在或不在公司表中。只有當公司尚不存在時才爲公司創建新記錄。
謝謝,它的工作 –