以下是我的模型結構創建記錄使用通過聯想和nested_form_for軌
role.rb
has_many :user_roles
has_many :users, through: :user_roles
has_many :companies, through: :user_roles
user.rb
has_one :user_role, dependent: :destroy
has_one :role, through: :user_role
has_one :company, through: :user_role
company.rb
has_many :user_roles, dependent: :destroy
has_many :users, through: :user_roles
has_many :roles, through: :user_roles
user_role.rb
belongs_to :user
belongs_to :role, optional: true
belongs_to :company
我想創造紀錄使用的關聯和嵌套形式和現在的我能夠與使用嵌套的用戶一起創建公司表單,但我也想爲用戶創建user_role。
我在公司模型中包含了accepts_nested_attributes_for :users
。 並使用fields_for
以公司新形式創建用戶。
下面是我的形式
<%= form_for @company, html: { multipart: true } do |f| %>
<% if company.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:</h2>
<ul>
<% company.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field form-group">
<%= f.label :name %>
<%= f.text_field :name, class: :"form-control" %>
</div>
<div class="field form-group">
<%= f.label :website %>
<%= f.text_field :website, class: :"form-control" %>
</div>
<div class="field form-group">
<%= f.label :phone %>
<%= f.text_field :phone, class: :"form-control" %>
</div>
<div class="field form-group">
<%= f.label :description %>
<%= f.text_area :description, class: :"form-control" %>
</div>
<div class="field form-group">
<%= f.file_field :company_image %>
</div>
<%= f.fields_for :users do |builder| %>
<%= render "users_fields", :f => builder %>
<% end %>
<div class="actions">
<%= f.submit class: :'btn btn-default' %>
</div>
<% end %>
眼下,在創建公司時,未創建USER_ROLE。我不知道如何繼續。
任何指導將不勝感激。提前致謝。
'不創建user_role',所以必須有某種錯誤消息或原因的,爲什麼不創建它。包括你的控制器代碼,包括'@ company.errors.full_messages'的輸出和檢查你的參數如何顯示。也許'user_role'不是'saving',因爲它是無效的。 'user_role'有'belongs_to:user'和'belongs_to:role,可選:true'。角色的存在驗證將被跳過,但您需要有一個有效的「用戶」。如果您將'user_role'賦予屬於未保存用戶的'user_id',則驗證將失敗。 –
感謝您的快速回復@Fabrizio, 我驗證了用戶。 UserRole是用戶和公司的第三張表格。 user_role的字段是user_id,role_id和company_id。 它使用user_id和company_id創建user_role,但不包括role_id到user_role記錄中。 請注意強參數 'params.require(:company).permit(:name,:website,:phone,:description,:company_image,users_attributes:[:email,:first_name,:last_name,:phone,:string ,:birth_date,:join_date,:gender,:password,:password_confirmation])' – wish
'user_role belongs_to user'。 'user_role.user_id'必須對應現有'user'的'id'。 'users'中一行的字段'id'。如果你試圖保存'user_role'並且'user'還沒有被保存,你將會觸發一個驗證錯誤,'user_role'將不會被保存。在創建'user_role'之前保存'user' –