如何解决Rails - 创建对象的新实例时搜索/显示可用选项
我与每个列表条目的一部电影建立了一对多关系,其中可以在列表条目中使用电影。我的 list_entries 表有一个 movie_id 和一个 list_id。 database schema
我在列表中嵌套了 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,:update]
resources :lists,:destroy] do
resources :list_entries
end
end
现在我可以创建和销毁列表条目,但我必须手动指定电影 ID。 我想要实现的 UX 是让用户能够从我的 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 %>
我的列表条目控制器:
class ListEntriesController < ApplicationController
before_action :find_list,only: [:index,: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 %>
我认为它应该根据电影标题进行标记,但如果没有,您可能需要在电影模型中指定 #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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。