Rails nested forms & # 8594; different treatment depending on the value
I have this tricky question regarding nested forms. Just tell me I have the following models:
- a restaurant
- employees in which employees belong to the restaurant.
I also have two types of employees in the employee model,
- Managers
- Staff
managers
denoted by an attribute manager
in the model employees
, it is boolean
.
When I go to edit the list of employees for each restaurant, it is through a nested form, that is:
<%= f.simple_fields for :employees do |f| %>
<%= render 'employee_fields', :f => f %>
<% end %>
MY QUESTION : Is there a way to render different partial forms depending on the type of employee? For example, if the current employee is a manager, then
<%= render 'manager_fields', :f => f %>.
Otherwise, if the current employee is a staff, then
<%= render 'staff_fields', :f => f %>.
source to share
Yes, using the ternary operator:
<%= render f.object.manager? ? 'manager_fields' : 'staff_fields' , :f => f %>
If you can change your design, I have a better solution for you. What follows:
Use Rails enum .
Add a field desgination
as an integer field in your model Employee
using migration.
Then inside the model:
enum designation: [ :staff, :manager ]
Then you will store the word in a column designation
, either manager
(value is 1) or staff
(value is 0). Now inside the call to the view <%= render f.object.desgination , :f => f %>
. And you have to have _manager.html.erb
, and _staff.html.erb
2 partial.
And you're done!
source to share
Yes, but it might look a little ugly:
<%= f.simple_fields for :employees do |f| %>
<%= render (f.object.manager? ? 'manager_fields' : 'staff_fields'), :f => f %>
<% end %>
I would probably create a helper method, for example in a file, ApplicationHelper
or EmployeesHelper
:
def get_employee_partial(employee)
employee.manager? ? 'manager_fields' : 'staff_fields'
end
and then in the form:
<%= render get_employee_partial(f.object), :f => f %>
source to share
You can achieve conditional rendering by doing something like the following:
<%= f.simple_fields for :employees do |f| %>
<% if f.object.manager? %>
<%= render 'manager_fields', :f => f %>
<% elsif f.object.staff? %>
<%= render 'staff_fields', :f => f %>
<% end %>
<% end %>
If you plan to have only the role manager
and staff
in your model, the Employee, you can simplify it by using a three-dimensional operator, for example, in response R_O_R.
You can separate the conditional logic from your view template. You can do this by creating a helper method shown in Surya's answer.
Hope it helps!
source to share