因此,這裏有我的模型:通過has_one和belongs_to將_existing_對象與用戶關聯起來?
user.rb: has_one :interview_slot
interview_slot.rb:belongs_to :user
的interview_slot
有start_time
,一個end_time
和available
布爾值。
舉例來說,我已經生成了一個20 interview_slot
實例的列表,我想要做的就是讓我的用戶從下拉框中選擇其中的一個。
我先檢查用戶是否已經接受記者採訪時槽:
@interview_slot = find_interview_slot(@rushee)
def find_interview_slot(user)
return InterviewSlot.find_by(user_id: user.id)
rescue
nil
end
如果@interview_slot
爲nil
,然後我要顯示所有的採訪槽仍處於一個下拉框available
的列表,並且我希望用戶能夠選擇其中一個採訪插槽,點擊提交,並且將指定的InterviewSlot
與用戶相關聯。我的問題是,我該如何編寫這樣做的表單?我只熟悉像@user.interview_slots.build
這樣的電話,並且打電話form_for
,比如:form_for(@interview_slot) do |f|
,但顯然我不想在這種情況下構建新的interview_slot,我只想將現有的interview_slot與用戶關聯起來。
任何見解?謝謝。
編輯:我也有一個實例變量,是所有InterviewSlots尚未與用戶關聯的集合:@available_slots = InterviewSlot.where(user_id: nil)
;我只是不知道如何製作讓用戶從這個集合中選擇一個插槽並將該插槽與用戶相關聯的表格。
編輯2:
我現在所擁有的這樣的代碼:
<%= form_for(@interview_slot) do |f| %>
<% slots_for_select = {}
@available_slots.each do |slot|
slots_for_select[slot.start_time.strftime("%a. %D | %l:%M %p")] = slot
end %>
<%= select_tag(:interview_slot, options_for_select(slots_for_select)) %>
<%= f.submit "Schedule Interview", class: "btn btn-sm" %>
<% end %>
這給了我所有可用的採訪插槽的下拉框,但問題是,再一次,這@interview_slot
被設置等於到@user.interview_slots.build(interview_slot_params)
在控制器中 - 我如何使用@user
的id更新所選的interview_slot
而不是創建新的interview_slot?