如何在编辑表单中预先填充collection_check_boxes?

2024-03-09

GitHub 仓库:https://github.com/Yorkshireman/mywordlist https://github.com/Yorkshireman/mywordlist

我用谷歌搜索了一下这个。我确信有一种方法,可能需要在 html 选项哈希中添加一些代码,但我无法解决。有任何想法吗?

当访问具有一个或多个类别的 Word 的 _edit_word_form.html.erb 部分时,类别复选框全部未选中,要求用户再次选择它们,即使他们不想更改类别。

:title 和 :description 的文本字段是预先填充的(幸运的是)。

_edit_word_form.html.erb:

<%= form_for(@word) do %>

  <%= fields_for :word, @word do |word_form| %>
    <div class="field form-group">
      <%= word_form.label(:title, "Word:") %><br>
      <%= word_form.text_field(:title, id: "new_word", required: true, autofocus: true, class: "form-control") %>
    </div>

    <div class="field form-group">
      <%= word_form.label(:description, "Definition:") %><br>
      <%= word_form.text_area(:description, class: "form-control") %>
    </div>
  <% end %>


  <%= fields_for :category, @category do |category_form| %>
    <% if current_user.word_list.categories.count > 0 %>
      <div class="field form-group">
        <%= category_form.label(:title, "Choose from existing Categories:") %><br>
        <%= category_form.collection_check_boxes(:category_ids, current_user.word_list.categories.all, :id, :title) do |b| %>
          <%= b.label(class: "checkbox-inline") { b.check_box + b.text } %>
        <% end %>
      </div>
    <% end %>

    <h4>AND/OR...</h4>

    <div class="field form-group">
      <%= category_form.label(:title, "Create and Use a New Category:") %><br>
      <%= category_form.text_field(:title, class: "form-control") %>
    </div>
  <% end %>

  <div class="actions">
    <%= submit_tag("Update!", class: "btn btn-block btn-primary btn-lg") %>
  </div>
<% end %>

words/index.html.erb的相关部分:

<% current_user.word_list.words.alphabetical_order_asc.each do |word| %>
              <tr>
                <td>
                  <%= link_to edit_word_path(word) do %>
                    <%= word.title %>
                    <span class="glyphicon glyphicon-pencil"></span>
                  <% end %>
                </td>
                <td><%= word.description %></td>
                <td>
                  <% word.categories.alphabetical_order_asc.each do |category| %>
                    <a class="btn btn-info btn-sm", role="button">
                      <%= category.title %>
                    </a>
                  <% end %>
                </td>
                <td>
                  <%= link_to word, method: :delete, data: { confirm: 'Are you sure?' } do %>
                    <span class="glyphicon glyphicon-remove"></span>
                  <% end %>
                </td>
              </tr>
            <% end %>

单词控制器.rb:

class WordsController < ApplicationController
  before_action :set_word, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  # GET /words
  # GET /words.json
  def index
    @words = Word.all
    @quotes = Quote.all
  end

  # GET /words/1
  # GET /words/1.json
  def show
  end

  # GET /words/new
  def new
    @word = current_user.word_list.words.build
  end

  # GET /words/1/edit
  def edit
  end

  # POST /words
  # POST /words.json
  def create
    @word = Word.new(word_params)

    respond_to do |format|
      if @word.save
        format.html { redirect_to @word, notice: 'Word was successfully created.' }
        format.json { render :show, status: :created, location: @word }
      else
        format.html { render :new }
        format.json { render json: @word.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /words/1
  # PATCH/PUT /words/1.json
  def update
    #need to first remove categories from the word
    @word.categories.each do |category|
      @word.categories.delete category
    end

    #then push categories in from the category_params
    if params["category"].include?(:category_ids)
      (params["category"])["category_ids"].each do |i|
        next if i.to_i == 0
        @word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))
      end
    end

    if category_params.include?(:title) && ((params["category"])["title"]) != ""
      @word.categories << current_user.word_list.categories.build(title: (params["category"])["title"])
    end

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

  # DELETE /words/1
  # DELETE /words/1.json
  def destroy
    @word.destroy
    respond_to do |format|
      format.html { redirect_to words_url, notice: 'Word was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_word
      @word = Word.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def word_params
      params.require(:word).permit(:title, :description, :category_ids)
    end

    def category_params
      params.require(:category).permit(:title, :category_ids, :category_id)
    end
end

类别_控制器.rb:

class CategoriesController < ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]

  # GET /categories
  # GET /categories.json
  def index
    @categories = Category.all
  end

  # GET /categories/1
  # GET /categories/1.json
  def show
  end

  # GET /categories/new
  def new
    @category = current_user.word_list.categories.build
  end

  # GET /categories/1/edit
  def edit
  end

  # POST /categories
  # POST /categories.json
  def create
    @category = Category.new(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to @category, notice: 'Category was successfully created.' }
        format.json { render :show, status: :created, location: @category }
      else
        format.html { render :new }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /categories/1
  # PATCH/PUT /categories/1.json
  def update
    respond_to do |format|
      if @category.update(category_params)
        format.html { redirect_to @category, notice: 'Category was successfully updated.' }
        format.json { render :show, status: :ok, location: @category }
      else
        format.html { render :edit }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /categories/1
  # DELETE /categories/1.json
  def destroy
    @category.destroy
    respond_to do |format|
      format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_category
      @category = Category.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def category_params
      params.require(:category).permit(:title, :word_list_id, :category_ids)
    end
end

word_lists_controller.rb:

class WordListsController < ApplicationController
  before_action :set_word_list, only: [:show, :edit, :update, :destroy]


  def from_category
    @selected = current_user.word_list.words.joins(:categories).where( categories: {id: (params[:category_id])} )
    respond_to do |format|
      format.js
    end
  end

  def all_words
    respond_to do |format|
      format.js
    end
  end

  # GET /word_lists
  # GET /word_lists.json
  def index
    @word_lists = WordList.all
  end

  # GET /word_lists/1
  # GET /word_lists/1.json
  def show
    @words = Word.all
    @word_list = WordList.find(params[:id])
  end

  # GET /word_lists/new
  def new
    @word_list = WordList.new
  end

  # GET /word_lists/1/edit
  def edit
  end

  # POST /word_lists
  # POST /word_lists.json
  def create
    @word_list = WordList.new(word_list_params)

    respond_to do |format|
      if @word_list.save
        format.html { redirect_to @word_list, notice: 'Word list was successfully created.' }
        format.json { render :show, status: :created, location: @word_list }
      else
        format.html { render :new }
        format.json { render json: @word_list.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /word_lists/1
  # PATCH/PUT /word_lists/1.json
  def update
    respond_to do |format|
      if @word_list.update(word_list_params)
        format.html { redirect_to @word_list, notice: 'Word list was successfully updated.' }
        format.json { render :show, status: :ok, location: @word_list }
      else
        format.html { render :edit }
        format.json { render json: @word_list.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /word_lists/1
  # DELETE /word_lists/1.json
  def destroy
    @word_list.destroy
    respond_to do |format|
      format.html { redirect_to word_lists_url, notice: 'Word list was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_word_list
      @word_list = WordList.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def word_list_params
      params[:word_list]
    end
end

单词列表.rb:

class WordList < ActiveRecord::Base

    belongs_to :user

    has_many :words

    has_many :categories

end

word.rb:

class Word < ActiveRecord::Base

  belongs_to :word_list

  has_and_belongs_to_many :categories

  validates :title, presence: true

  scope :alphabetical_order_asc, -> { order("title ASC") }

end

类别.rb:

class Category < ActiveRecord::Base

    has_and_belongs_to_many :words

    belongs_to :word_list

    validates :title, presence: true

    scope :alphabetical_order_asc, -> { order("title ASC") }

end

架构.rb:

ActiveRecord::Schema.define(version: 20150609234013) do

  create_table "categories", force: :cascade do |t|
    t.string   "title"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "word_list_id"
  end

  add_index "categories", ["word_list_id"], name: "index_categories_on_word_list_id"

  create_table "categories_words", id: false, force: :cascade do |t|
    t.integer "category_id"
    t.integer "word_id"
  end

  add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
  add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"

  create_table "quotes", force: :cascade do |t|
    t.text     "content"
    t.string   "author"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

  create_table "word_lists", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  create_table "words", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.integer  "word_list_id"
  end

  add_index "words", ["word_list_id"], name: "index_words_on_word_list_id"

end

路线.rb:

Rails.application.routes.draw do
  resources :quotes
  resources :categories
  resources :words
  devise_for :users, controllers: { registrations: "users/registrations" }

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'
  root 'pages#home'

  post 'create_word_and_category' => 'new_word#create_word_and_category'
end

讨论可能不再活跃,但我会为未来的访客分享我的答案。

添加“{checked:@array.map(&:to_param)}”选项作为collection_check_boxes的最后一个参数可能会解决您的问题。参考这个link https://github.com/bootstrap-ruby/rails-bootstrap-forms/issues/151.

例子:
假设您有软件型号和平台(操作系统)型号,并且想要选择一个或多个支持您的软件的操作系统。

#views/softwares/edit.html.erb

<%= form_for @software do |f| %>
  ...
  <%= f.label :supported_platform %>
  <%= f.collection_check_boxes(:platform_ids, @platforms, :id, :platform_name, { checked: @software.platform_ids.map(&:to_param) }) %>
  ...
  <%= f.submit "Save", class: 'btn btn-success' %>
<% end %>

note:
@software.platform_ids 应该是一个数组。如果您使用 SQLite,则在提取数据时必须将字符串转换为数组。我用 SQLite 测试了它并确认也可以工作。看my post http://www.letmefix-it.com/2017/08/11/how-to-use-collection_check_boxes-ruby-on-rails/了解更多详情。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在编辑表单中预先填充collection_check_boxes? 的相关文章

随机推荐

  • Javascript - 如何替换子字符串?

    这是一个简单的问题 我想使用 Javascript 在客户端将一个子字符串替换为另一个子字符串 原始字符串是 original READ ONLY 我想更换 READ ONLY with READ WRITE 请问有什么快速答复吗 可能有一
  • C# / F# 性能比较

    网络上是否有任何 C F 性能比较来显示新 F 语言的正确用法 自然 F 代码 例如函数式 不可变 比自然 命令式 可变面向对象 C 代码慢 然而 这种 F 比通常的 C 代码要短得多 显然 这是一个权衡 另一方面 在大多数情况下 您可以实
  • VHDL 中数组的硬件表示

    使用 VHDL 我想要一些寄存器 每个寄存器存储 16 位 所以我发现VHDL有一个内置数组 我想用它来存储iy中每个元素的16位 所以我想知道VHDL是否将此数组映射到实际寄存器 简短的回答是否定的 数组类型不映射到寄存器 长答案 VHD
  • 升级到 OSX Mojave 后 GCP 将无法工作

    升级到 OSX Mojave Developer beta 2 后 每次使用 GCP 以及重新安装时都会出现错误 ERROR gcloud failed to load No module named zlib gcloud main im
  • php中超过24小时的字符串

    有一个语法错误 您的变量名称是 hour 但最后您使用了 hours time1 strtotime 02 40 00 time2 strtotime 34 20 00 diff time2 time1 hour floor diff 60
  • QT:将我的域对象基于 QObject 是一个好主意吗?

    我对于将 QT 框架与 C 结合使用相当陌生 我想知道 将我的域类基于 QObject 是一个好主意吗 或者我应该只对层次结构中较高的类执行此操作 更接近用户界面级别 QT文档对此并不清楚 摘自QT文档 元对象系统是 C 的扩展 使该语言更
  • 在 iOS 中 - 如何使 UILabel 适合其文本而不改变其位置?

    我正在打电话sizeToFit on a UILabel其中有右对齐的文本 它缩小了高度和宽度UILabel并将文本调整到左上角UILabel 现在 的位置UILabel是不正确的 我怎样才能使UILabel留在原来的位置 右对齐 还是移动
  • 如何使用 mod_rewrite/htaccess 通过锚点检测并重定向 URL?

    我见过很多相反的例子 但我希望从锚点 哈希 URL 转到非锚点 URL 如下所示 From http old swfaddress site com page name To http new html site com page name
  • 删除laravel中的特定迁移

    根据 laravel 文档 要回滚最新的迁移操作 您可以使用 rollback 命令 此命令回滚最后 批次 的迁移 其中可能包括多个迁移文件 php artisan migrate rollback 您可以通过向回滚命令提供步骤选项来回滚有
  • 无法使用 Java 1.8 在 JBoss 5.1 中编译 JSP 文件

    无法使用 Java 1 8 在 JBoss 5 1 中编译 JSP 文件 能够编译常规Java文件 甚至能够完成没有JSP的Spring项目 如果我们保留这些 JSP 文件的编译类文件 它就可以正常工作 以下是我尝试运行 JSP 文件时遇到
  • 如何使用 React.js 循环 JSX 中的对象

    所以我有一个 React js 组件 我想循环遍历我导入的对象以向其添加 HTML 选项 这是我尝试过的 既丑陋又不起作用 import React from react import AccountTypes from data Acco
  • 使用 Django RequestFactory 而不是表单数据的 POST 文档

    我想构建一个测试中间件的请求 但我不希望 POST 请求始终假设我正在发送表单数据 有没有办法设置request body根据生成的请求django test RequestFactory 即 我想做类似的事情 from django te
  • 自动将 Spring @RequestMapping 注释记录到一个位置?

    Javadoc 非常适合扫描所有源文件并创建 HTML 页面来查看它 我想知道是否有一个类似的工具可以遍历所有 Spring 控制器并收集所有用 RequestMapping 注释的方法并生成一个列出它们的 HTML 页面 有点像开发人员的
  • WKWebView LayoutConstraints 问题

    我创建了一个简单的网络视图应用程序 但有一个小问题我无法修复 它加载第一页没有问题 当我单击第一个输入时 程序崩溃 错误代码如下 2017 10 28 23 50 54 289690 0400 BFI Schools 68425 38856
  • SASL 握手期间出现意外的 METADATA 类型的 Kafka 请求

    我正在尝试使用 SASL Plain 将 Kafka Java 客户端连接到 Kafka 代理 但是当我尝试从生产者发送消息时 Kafka 服务器记录以下错误 2020 04 30 14 48 14 955 INFO SocketServe
  • 使用POSTMAN获取授权码-OAuth2.0

    我正在使用POSTMAN来测试OAuth2 0授权码流程对于 MSGraph 以下是相同的详细信息 验证码网址 https login microsoftonline com tenant id oauth2 authorize https
  • Tomcat环境中如何保存名称-值对?

    我们有一个 servlet 它需要某些变量 如密码 加密盐等 而不是永久保存在文件系统上 这就是我们目前所做的 总结 在初始化期间 Perl 脚本将 ReadMode 设置为 2 以屏蔽 stdout echo 提示用户输入变量 过滤已知文
  • 检查元素上是否有事件侦听器。没有 jQuery [重复]

    这个问题在这里已经有答案了 如果我像下面的代码一样使用内联函数 如何检查元素上是否有事件侦听器 因为我有一个函数可以调用该函数并添加事件侦听器 但它会导致重复的事件侦听器导致它触发函数两次 如果事件侦听器已经存在 我该如何检查它以便阻止它添
  • Rails 3.1 中的无表模型

    好像this http railscasts com episodes 193 tableless model该方法在 Rails 3 1 中不再适用 那么 有人有可行的解决方案吗 其实我已经找到这个了gist https gist git
  • 如何在编辑表单中预先填充collection_check_boxes?

    GitHub 仓库 https github com Yorkshireman mywordlist https github com Yorkshireman mywordlist 我用谷歌搜索了一下这个 我确信有一种方法 可能需要在 h