[英]Rails - Searching/showing available option when creating new instance of an object
我與每個列表條目的一部電影建立了一對多的關系,其中一部電影可以在列表條目中使用。 我的 list_entries 表有一個 movie_id 和一個 list_id。 數據庫模式
我已經將 list_entries 嵌套在列表中,因此我可以在創建新實例時直接傳遞 list_id。
Rails.application.routes.draw do
devise_for :users
root to: 'pages#home'
resources :movies, only: [:new, :index, :create, :show, :destroy, :edit, :update]
resources :users, only: [:show, :edit, :update]
resources :lists, only: [:new, :create, :show, :index, :destroy] do
resources :list_entries
end
end
現在我可以創建和銷毀列表條目,但我必須手動指定電影 ID。 我想要實現的用戶體驗是讓用戶能夠從我的 list_entries/new 表單中搜索電影,但我什至不知道從哪里開始。 現在的形式:
<%= simple_form_for @list_entry, url: list_list_entries_path do |f| %>
<%= f.input :comment %>
<%= f.input :movie_id %>
<%= f.submit "Add", class: "btn devise-button" %>
<% end %>
我的列表條目 controller:
class ListEntriesController < ApplicationController
before_action :find_list, only: [:index, :create, :show, :new, :destroy]
def new
@list_entry = ListEntry.new
end
def index
@list_entries = ListEntry.where(list: @list)
end
def show
@list_entry = ListEntry.find(params[:id])
end
def destroy
@list_entry = ListEntry.find(params[:id])
@list_entry.destroy
redirect_to list_list_entries_path
end
def create
@list_entry = ListEntry.new(entry_params)
@list_entry.list_id = params[:list_id]
if @list_entry.save
redirect_to list_list_entries_path
else
render 'new'
end
end
private
def find_list
@list = List.find(params[:list_id])
end
def entry_params
params.require(:list_entry).permit(:comment, :movie_id)
end
end
如果不想在表單中手動指定movie_id,可以使用simple_form_for 關聯助手:
<%= f.input :comment %>
<%= f.association :movie %>
我認為它應該根據電影標題進行標記,但如果沒有,您可能必須在電影 model 中指定 #to_label 方法。
或者,您可以在 #new 操作中查詢電影,並使用它們在您的視圖中執行您喜歡的任何操作:
def new
@list_entry = ListEntry.new
@movies = Movie.all # or whatever query you think is relevant
end
#collection_select 文檔在這里可能有用: https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.