i have a relation like a teacher can have at max three students. I have a association like teacher has many students and student belongs to teacher. so while updating a teacher record im showing a form where student 1 followed by a text filed and student 2 followed by a test field and student 3 followed by a text filed.
the problem here is always last student data only getting saved. while updating. so how can i add a form so that it creates a student record if there are no records and update records if there is already records present.
how the form should be and the controller logic for this? i dont want to use nested form.
[params[:student1],params[:student2],params[:student3]].each do |student|
@teacher.student.update_attributes(student)
end
and form is like
<% students = @teacher.students %>
<% if students.present? %>
<% students.each do |student| %>
<div class="col-sm-3">
<%= label_tag "student", "name*" %>
<%=
text_field_tag(
"student[name]",
student.name,
class: "form-control form-control-inline"
)
%>
</div>
<% end %>
<% else %>
<div class="col-sm-3">
<%= label_tag "name", "name*" %>
<%=
text_field_tag(
"student1[name]",
"",
class: "form-control form-control-inline"
)
%>
</div>
<div class="col-sm-3">
<%= label_tag "name", "name*" %>
<%=
text_field_tag(
"student2[name]",
"",
class: "form-control form-control-inline"
)
%>
</div>
<div class="col-sm-3">
<%= label_tag "name", "name*" %>
<%=
text_field_tag(
"student3[name]",
"",
class: "form-control form-control-inline"
)
%>
</div>
<% end %>
can some one help me what i need to do? should i use build method in controller ? instead of update attributes ? if i use build will it work like a create method when there are no records and acts as a update method when there are 3 student records.
I think
find_or_create_byis what you are looking for. https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by