我有一个用户仪表板控制器,该控制器在同一视图内具有多个远程表单,供用户更新其他属性:
class CustomerDashboardController < ApplicationController
def settings
end
end
//settings.html.erb
<div class="info__item">
<p class="info-item__heading">Name: <%= link_to "Edit", "", class: "info-edit__link", id: "user-edit__name", remote: true %></p>
</div>
<div class="info__item">
<p class="info-item__heading">Email: <%= link_to "Edit", "", class: "info-edit__link", id: "user-edit__Email", remote: true %></p>
</div>
jquery ujs触发器存在于*.js.erb
文件中,其名称与表单所包含的相应动作/视图模板相匹配:
//customer-dashboard/settings.js.erb
$('#user-edit__name').hide().after('<%= j render("user-edit-name-form") %>');
$('#user-edit__address').hide().after('<%= j render("user-edit-address-form") %>');
每种形式均可正确呈现和更新属性,
但是,当单击带有remote: true
的单个链接时,它将同时呈现页面上的每个表单部分,而不是仅显示与该链接相关的具有唯一id: ""
答案 0 :(得分:0)
根据@NM Pennypacker的建议,我提出了一个解决方案,即完全跳过使用remote: true
,而只使用Javascript来切换多个表单部分的可见性。
我的JavaScript解决方案:
allEditButtons = document.querySelectorAll('.info-edit__link');
const showFormListener = event => {
event.preventDefault();
toggleAdjacentFormVisibility(event);
};
allEditButtons.forEach(element => {
element.addEventListener('click', showFormListener);
});
function toggleAdjacentFormVisibility(event) {
event.target.parentElement.nextElementSibling.classList.toggle(
'info__is-not-visible'
);
event.target.parentElement.nextElementSibling.nextElementSibling.classList.toggle(
'info__is-visible'
);
}
视图:
<div class="info__item">
<p class="info-item__heading">Email: <%= link_to "Edit", "", class: "info-edit__link" %></p>
<p class="info-item__info">
<%= @user.email %>
</p>
<div class="info-item__form-container">
<%= render ('user-edit-email-form') %>
</div>
</div>
<div class="info__item">
<p class="info-item__heading">Email: <%= link_to "Edit", "", class: "info-edit__link" %></p>
<p class="info-item__info">
<%= @user.phone %>
</p>
<div class="info-item__form-container">
<%= render ('user-edit-phone-form') %>
</div>
</div>
CSS:
.info__is-visible {
display: block;
}
.info__is-not-visible {
display: none;
}