0

我很抱歉,因为这看起来像一个翻倍的帖子,但我看到了很多其他线程,我无法理解我在做什么。

我正在尝试制作一个 has_and_belongs_to_many,但我被卡住了。

我设法使表单显示正确的信息,但我不知道如何保存它。

我有:

宝珠类:

class Orb < ActiveRecord::Base
  attr_accessible :descr, :id, :nome, :orb_type_id, :orbt

  validates_presence_of :nome, :orb_type_id
  validates :nome, :uniqueness => true

  belongs_to :orb_type

  has_and_belongs_to_many :books
end

书类:

class Book < ActiveRecord::Base
  attr_accessible :dataf, :datai, :descr, :id, :nome

  validates_presence_of :nome
  validates :nome, :uniqueness => true

  has_and_belongs_to_many :orbs

  # allows project page to add items via checkboxes
  accepts_nested_attributes_for :orbs

end

表单:

 <% @book.each do |book| %>
    <div>
      <%= check_box_tag "orb[book_ids][]", book.id, @orb.books.include?(book), id: dom_id(book) %>
      <%= book.nome %>
    </div>
  <% end %>

和控制器:

def new
  @book = Book.all
  @orb = Orb.new
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @orb }
  end
end
# GET /orbs/1/edit
def edit
  @orb = Orb.find(params[:id])
  @book = Book.all
end
# POST /orbs
# POST /orbs.json
def create
  @orb = Orb.new(params[:orb])
  respond_to do |format|
    if @orb.save
      format.html { redirect_to @orb, notice: 'save was successful' }
      format.json { render json: @orb, status: :created, location: @orb }
    else
      format.html { render action: "Novo" }
      format.json { render json: @orb.errors, status: :unprocessable_entity }
    end
  end
end
# PUT /orbs/1
# PUT /orbs/1.json
def update
  params[:orb][:book_ids] ||= []
  @orb = Orb.find(params[:id])
  respond_to do |format|
    if @orb.update_attributes(params[:orb])
      format.html { redirect_to @orb, notice: 'save was successful' }
      format.json { head :no_content }
    else
      format.html { render action: "Editar" }
      format.json { render json: @orb.errors, status: :unprocessable_entity }
    end
  end
end

有了这个,表单有一个带有正确值的复选框,但它不会被保存。我不知道我在做什么,有人可以解释我必须做什么吗?

4

1 回答 1

0

您需要一个连接表才能使用 has_and_belongs_to_many

class CreateTableBooksOrbs < ActiveRecord::Migration
    def change
    create_table :books_orbs, :id => false do |t|
      t.references :orb,  :null => false
      t.references :book, :null => false
    end
    add_index :books_orbs, [:book_id, :orb_id], :unique => true
  end
end

在这里查看我的工作版本:https ://github.com/senayar/books

于 2013-05-28T15:46:32.680 回答