首页 > 解决方案 > Rails - 创建对象的新实例时搜索/显示可用选项

问题描述

我与每个列表条目的一部电影建立了一对多的关系,其中一部电影可以在列表条目中使用。我的 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 %>

我的列表条目控制器:

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

标签: ruby-on-railsrubysimple-form

解决方案


如果不想在表单中手动指定movie_id,可以使用simple_form_for 关联助手:

<%= f.input :comment %>
<%= f.association :movie %>

我认为它应该根据电影标题进行标记,但如果没有,您可能必须在 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


推荐阅读