ruby-on-rails - 在 Ruby on Rails 中创建对象列表或数组

标签 ruby-on-rails ruby forms

我试图让我正在构建的网络应用程序的用户能够创建他们创建的对象列表。

例如,用户有一个对象列表,例如杂货,可以是从苹果到橙子再到果馅饼的任何东西。

然后我希望能够返回用户添加到数据库中的所有杂货,并通过选择应该在他们的杂货 list 上的那些来创建一个列表。

最好采用这样的样式,以便他们可以单击所需复选框的复选框,然后单击保存以创建新列表。

我研究了 belongs_to、has_many 关系并尝试创建一个包含许多杂货的列表对象,但我无法弄清楚该策略的表单部分。我将不胜感激任何/所有建议。谢谢!

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

杂货店模型:

class Item < ApplicationRecord
    belongs_to :list, optional: true
end

列表模型

class List < ApplicationRecord
    has_many :items
end

列表 Controller

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

不确定如何处理表单 - 正在尝试按照 http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box 的方式进行操作

最佳答案

我会通过实现第三个模型来解决这个问题,该模型保持杂货和列表之间的关联。然后您可以使用 :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

有了该模型结构,下面是一个用于创建新列表的 View 示例。

<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 %>

为了解释这里发生了什么,@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")

所以在上面的表格中,我替换了那些默认值,这样当一个复选框被选中时,它具有来自 item.id 的值,如果它没有被选中,则该值为空。结合List模型中accepts_nested_attributes_for的声明,我们说如果:item_id为空就应该拒绝,得到只创建ListItems的结果对于选中的项目。

最后一件事是允许 Controller 中的嵌套属性,如下所示:

def allowed_params
  params.require(:list).permit(list_items_attributes: [:item_id])
end

关于ruby-on-rails - 在 Ruby on Rails 中创建对象列表或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41561836/

相关文章:

ruby-on-rails - gem 安装 bcrypt (LoadError)

ruby-on-rails - Rails Geocoder 限制地区/国家

javascript - 提交表单和重定向不起作用

ruby-on-rails - 是否可以从本地主机直接连接到 Heroku 数据库?

ruby-on-rails - 模块中未定义的方法

ruby-on-rails - 如何在 Rails 4 上使用 Ajax?

java - Spring MVC 3 validator 不显示错误消息

php - 在 CMS 中插入表单 - <选项> 和页面

ruby-on-rails - Rails 3 多态关联与 foreign_type 列作为整数

JavaScript 数组转字符串