在Ruby on Rails中创建一个列表或对象数组

Kev*_*vin 5 ruby forms ruby-on-rails

我试图让我正在构建的Web应用程序的用户可以创建他们创建的对象列表.

例如,用户有一个对象列表,例如杂货,可以是从苹果到橙子到弹出式挞的任何东西.

然后,我希望我可以返回用户添加到数据库中的所有杂货,并通过选择应该在他们的购物清单上的那些来创建列表.

优选地,这将是一种样式,使得他们可以单击他们想要的复选框,然后单击"保存"以创建新列表.

我已经研究过belongs_to,has_many关系并尝试创建一个包含许多杂货的列表对象,但我无法弄清楚这个策略的形式部分.我很感激任何/所有建议.谢谢!

这是我目前的代码,我最初省略它,因为我不认为我在正确的道路上,但这里无论如何只是以防万一/提供更多的上下文:

杂货店型号:

class Item < ApplicationRecord
    belongs_to :list, optional: true
end
Run Code Online (Sandbox Code Playgroud)

列表模型

class List < ApplicationRecord
    has_many :items
end
Run Code Online (Sandbox Code Playgroud)

List控制器

class ListsController < ApplicationController
  before_action :authenticate_user!
  layout 'backend'

  def index
    @lists = List.where(user_id: current_user.id)
  end

  def show
  end

  def new
    @list = List.new
  end

  def edit
  end

  def create
    @list = List.new(list_params)
    @list.user = current_user

    if @list.save
      redirect_to list_path(@list.id), notice: 'List was successfully created.'
    else
      redirect_to list_path(@list.id), notice: 'List was not created.'
    end
  end

  def update
    respond_to do |format|
      if @list.update(list_params)
        format.html { redirect_to @list, notice: 'List was successfully updated.' }
        format.json { render :show, status: :ok, location: @list }
      else
        format.html { render :edit }
        format.json { render json: @list.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @list.destroy
    respond_to do |format|
      format.html { redirect_to lists_url, notice: 'List was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Never trust parameters from the scary internet, only allow the white list through.
    def list_params
      params.require(:list).permit(:name, :items)
    end
end
Run Code Online (Sandbox Code Playgroud)

不确定如何处理表单 - 正在尝试http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box

Dan*_*nne 2

我将通过实现第三个模型来解决这个问题,该模型保持杂货和列表之间的关联。然后您可以使用 来以表单形式处理它:accepts_nested_attributes_for

举个例子,我将如何构建模型:

class List < ApplicationRecord
  has_many :list_items,   inverse_of: :list
  has_many :items,        through: :list_items

  # This allows ListItems to be created at the same time as the List, 
  # but will only create it if the :item_id attribute is present
  accepts_nested_attributes_for :list_items, reject_if: proc { |attr| attr[:item_id].blank? }
end

class Item < ApplicationRecord
  has_many :list_items
  has_many :lists,        through: :list_items
end

class ListItem < ApplicationRecord
  belongs_to :list, inverse_of: :list_items
  belongs_to :item
end
Run Code Online (Sandbox Code Playgroud)

模型结构就位后,下面是用于创建新列表的视图示例。

<h1>New List</h1>
<%= form_for @list do |f| %>
  <% @items.each_with_index do |item, i| %>
    <%= f.fields_for :list_items, ListItem.new, child_index: i do |list_item_form| %>
      <p>
        <%= list_item_form.check_box :item_id, {}, item.id, "" %> <%= item.name %>
      </p>
    <% end %>
  <% end %>
  <p>
    <%= f.submit 'Create List' %>
  </p>
<% end %>
Run Code Online (Sandbox Code Playgroud)

为了解释这里发生的事情,@items是一个预加载的变量,其中包含可以添加到列表中的所有项目。我循环遍历每个项目并将其手动传递给 FormBuilder 方法fields_for

因为我手动执行此操作,所以我必须:child_index同时指定,否则每个复选框都会获得name="list[list_item_attributes][0][item_id]"与前一项相同的名称属性(即),并且在提交到服务器时它们会覆盖彼此的值。

FormBuilder 方法check_box具有以下声明:

def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
Run Code Online (Sandbox Code Playgroud)

因此,在上面的表单中,我替换了这些默认值,以便当选中复选框时,它的值来自item.id,如果未选中,则该值为空。将其与 List 模型中的声明结合起来accepts_nested_attributes_for,其中我们说如果 为:item_id空,则应拒绝它,并且我们得到仅为选中的项目创建 ListItems 的结果。

使这项工作起作用的最后一件事是允许控制器中的嵌套属性,如下所示:

def allowed_params
  params.require(:list).permit(list_items_attributes: [:item_id])
end
Run Code Online (Sandbox Code Playgroud)