0
我試圖讓一個嵌套窗體顯示空字段(當前存在的數據正在顯示)。解決這部分,看看更新。rails嵌套窗體問題
此外,我試圖找到一種方法來編輯每個嵌套的表單條目一次,目前我只能得到編輯,以編輯時顯示在同一表單上的所有嵌套表單條目。理想情況下,我希望每個職位旁邊的鏈接能夠編輯只有一個條目,而不是在編輯模式下打開的所有條目。
用戶控制器
# renders the users/new.html.erb form
def new
@user = User.new
@user.work_histories.build # used for nested attributes in forms
end
# renders the users/edit.html.erb view form
def edit
@user = User.find(params[:id])
@user.work_histories.build # used for nested forms
end
# white listed form attributes for user and also for nested attributes (work history, qualifications, etc...).
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :phone, :current_job_title, :password, :password_confirmation,
work_histories_attributes: [:user_id, :id, :job_title, :company, :description, :city, :state,:start_date, :end_date])
end
用戶模型用戶
# allows for nested attributes in the user views.
accepts_nested_attributes_for :work_histories, allow_destroy: true,
reject_if: lambda {|attributes| attributes['job_title'].blank?}
WorkHistory模型
belongs_to :user, optional: true
展示圖。該模式顯示first_name的用戶字段,但不顯示工作歷史記錄字段。
<!-- modal -->
<div class="modal fade" id="experienceModal" tabindex="-1" role="dialog" aria-labelledby="experienceModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times fa-fw" aria-hidden="true"></i></button>
<h4 class="modal-title" id="myModalLabel">Experience</h4>
</div>
<div class="modal-body">
<!-- one-to-many nested attributes -->
<%= form_for(@user) do |f| %>
<%= f.label :first_name %>
<%= f.text_field :first_name, size: 40, autofocus: true, class: 'form-control' %>
<%= f.fields_for :work_histories do |ff| %>
<%= ff.label :job_title %>
<%= ff.text_field :job_title, size: 40, autofocus: true, class: 'form-control' %>
<% end %><!-- fields_for -->
<%= f.submit 'Save', class: 'btn btn-primary' %>
</div><!-- modal body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<% end %><!-- form_for -->
</div><!-- modal-content -->
</div><!-- modal dialog -->
</div><!-- modal -->
UPDATE: 好吧,我想通了,如何讓形式顯示空的,所以我可以有用戶數據,而不是表格與現有的用戶數據被顯示。只需在視圖中添加WorkHistory.new。
<%= form_for @user do |user_form| %>
<%= user_form.label :first_name %>
<%= user_form.text_field :first_name, autofocus: true, class: "form-control" %>
<%= user_form.fields_for :work_histories, WorkHistory.new do |wh_fields| %>
job: <%= wh_fields.text_field :job_title %>
<% end %>
<% end %>