繁体   English   中英

Ruby on Rails 当 A has_and_belongs_to_many B 时创建 AB 关系实例,反之亦然

[英]Ruby on Rails Create A-B relationship instance when A has_and_belongs_to_many B and vice versa

我有两个示例类:

# book.rb
class Book < ApplicationRecord
    has_and_belongs_to_many :tag
end

# tag.rb
class Tag < ApplicationRecord
  has_and_belongs_to_many :formula
end

如果我理解正确,这意味着我最终可以拥有带有许多书籍的标签和带有许多标签的书籍。 现在,我想在创建书籍时为书籍分配标签。

我在书籍/新页面上有一个多选下拉菜单,可以将这些标签发送到 controller,但我不知道一旦它们到达 controller 该怎么办。

  <div>
    <%= form.label :tags, style: "display: block" %>
    <%=  select_tag :tags, options_from_collection_for_select(@tags, :id, :name), multiple: true, prompt: "Select Tags" %>
  </div>

Controller 看起来像这样:

def create
    @Book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to book_url(@book), notice: "Book was successfully created." }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

当我使用表单制作一本书时,当我在 rails 控制台中检查最新一本书时,它没有任何标签。

我尝试将 @book.tag.build(tag_ids: book_params["tags"]) 放入您的创建方法中,但这没有用,我觉得我在叫错树。

您可以在Book model 中添加accepts_nested_attributes_for:tags 这样,当提交表单时, @book.save将为来自params[:books][:tags]的标签创建关联

# book.rb
class Book < ApplicationRecord
  has_and_belongs_to_many :tag
    
  accepts_nested_attributes_for :tags
end


参考: https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

如果要将现有标签分配给新书,可以在表单中使用select方法

<%= form.select :tag_ids, Tag.all.map { |p| [p.name, p.id] }, multiple: true, prompt: "Select Tags" %>

当然,您可以从 controller 传递@tags而不是Tag.all

如果您使用强参数,则需要在此处添加此参数,例如

params.require(:book).permit(
  # existed params,
  tag_ids: []
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM