recruitment
表在attendance
之间具有一对多关联project_site
表在“出勤”之间具有一对多关联。
在创建新的attendance
记录之前,我想检查是否存在任何记录。如果存在,我想显示attendance.status
否则我想显示表单代码以设置状态。我怎么用下面的代码做到这一点-
attendance_controller.rb
def new
@attendance = Attendance.new
@recruitment = Recruitment.all
end
def create
@attendance = Attendance.new(attendance_params)
respond_to do |format|
if @attendance.save
format.html { redirect_to new_project_site_attendance_path, notice: 'Attendance was marked successfully.' }
format.json { render :show, status: :created, location: @attendance }
else
format.html { render :new }
format.json { render json: @attendance.errors, status: :unprocessable_entity }
end
end
end
_ form.html.erb
<table>
<thead>
<tr>
<th>Name</th>
<% (1..(Time.days_in_month @project_site.attendance_month.strftime("%m").to_i)).each do |date| %>
<th><%= date %></th>
<% end %>
</tr>
</thead>
<tbody>
<% @recruitment.where(location: @project_site.site_id).each do |recruitment| %>
<tr>
<td><%= recruitment.name %></td>
<% (1..(Time.days_in_month @project_site.attendance_month.strftime("%m").to_i)).each do |date| %>
<td>
<%= form_with(model: attendance, :html => {:id => 'attendance-form-validation'}, url:[@project_site, @attendance], local: true) do |f| %>
<div>
<div class="wrapper-class">
<%= f.select :status, [['P', 1], ['A', 2], ['H', 3]], {}, { onchange: 'this.form.submit()', class: 'attendance-select-input' } %>
</div>
<div>
<%= f.hidden_field :attendance_date, value: (@project_site.attendance_month.strftime("%Y-%m")+"-"+date.to_s)%>
</div>
<%=f.hidden_field :recruitment_id, value: recruitment.id%>
<%=f.hidden_field :project_site_id, value: @project_site.id%>
</div>
<% end %>
</td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
我尝试过-
<% if @attendance.status != nil %>
<% else %>
<%# render form code %>
<% end %>
这对我不起作用。
obj = Attendance.find_or_create(attendance_id)
if !obj.status.nil? ?
@attendance = obj.status :
obj.update(attendance_params)
# find_or_create can expand to search by custom field
# This either finds an object by that id or creates a new skeleton of that object. (Just the id and the rest nil)
# Find the object in question, if the object in question's status is nil update the skeleton Attendance object with new data, else leave current data
# The .update might be .update_attributes since it's Rails 5