2014-01-22 60 views
0

因此,這裏有我的模型:通過has_one和belongs_to將_existing_對象與用戶關聯起來?

user.rb: has_one :interview_slot

interview_slot.rb:belongs_to :user

interview_slotstart_time,一個end_timeavailable布爾值。

舉例來說,我已經生成了一個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_slotnil,然後我要顯示所有的採訪槽仍處於一個下拉框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?

回答

0
# interview_slots_controller.rb 

def update 
    interview_slot = InterviewSlot.find(params[:interview_slot_id]) 
    interview_slot.user_id = your_current_user.id 
    interview_slot.save 
end 
相關問題