Rails collection_select,多对多不在连接表中创建条目

时间:2014-06-16 11:08:32

标签: ruby-on-rails ruby-on-rails-4 nested-forms fields-for

我正在开发一款类似图书馆预订应用的应用。我坚持建立一个嵌套的表格来添加一本新书。我得到了一对多关系(书籍图像等)的表格,但我也想选择并将现有作者与该书联系起来(一本书有很多作者,作者有很多书通过< / em>贡献表)与collection_select。

提交表单时,它不会使用book_id和author_id在连接表中创建条目。 (我设法在创建新作者时使用简单的text_entry字段,但collection_select不起作用。在将reject_if添加到accepts_nested_attributes之前,它一直创建一个空作用first_name和last_name的新作者并创建一个条目在这个空白的新作者的连接表中)

在这里,我的表格被剥夺了重要的部分

    <%= form_for @book do |f| %>

    <div class="panel panel-default">
        <div class="panel-body">
            <%= f.label :name, "Book title" %>
            <%= f.text_field :name %>
            <%= f.label :description %>
            <%= f.text_area :description, rows: 5 %>
            <%= f.label :year_of_publication %>
            <%= f.text_field :year_of_publication %>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-body">
            <h3>Add authors</h3>
            <h4>Choose from existing authors</h4>
            <%= f.fields_for :authors do |builder| %>
                <%= builder.collection_select( :id, Author.all, :id, :full_name, prompt: "Select from existing authors") %>
            <% end %>
        </div>
    </div>

    <%= f.submit "Submit", class: "btn btn-info" %>
<% end %>

这是当前为collection_select

呈现的HTML
<select id="book_authors_attributes_0_id" name="book[authors_attributes][0][id]"><option value="">Select from existing authors</option>
<option value="1">Berman, Jules J.</option>
<option value="2">Writerton, Andy R.</option>
<option value="3">Goldner, Merle</option>
<option value="4">Auer, Cordell</option>
<option value="5">Metz, Dewitt</option>
<option value="6">Leffler, Briana</option>
<option value="7">Trantow, Audra</option>
<option value="8">Murazik, Ebony</option>
<option value="9">Bahringer, Cale</option>
<option value="10">Schmitt, Wiley</option>
<option value="11">Casper, Zoe</option>

这是我的书模型。

class Book < ActiveRecord::Base
# default_scope -> { order('name ASC') }

validates :year_of_publication, presence: true
validates :description, presence: true
validates :name, presence: true

has_many :stock_items,      dependent: :destroy
has_many :libraries,        through: :stock_items
has_many :contributions,    dependent: :destroy 
has_many :authors,          through: :contributions
has_many :bookings,         through: :stock_items

has_many :book_images, dependent: :destroy
accepts_nested_attributes_for :book_images
accepts_nested_attributes_for :authors, :allow_destroy => true, :reject_if => proc {|attributes| attributes['last_name'].blank? }
accepts_nested_attributes_for :libraries
accepts_nested_attributes_for :stock_items
accepts_nested_attributes_for :contributions

validates :name, presence: true
# validate year of pub length to 4
end

我的作者模特。

class Author < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true

has_many :contributions, dependent: :destroy
has_many :books, through: :contributions

def full_name
    "#{last_name}, #{first_name}"
end

end

贡献模型(联接表)

class Contribution < ActiveRecord::Base
    belongs_to :author
    belongs_to :book

    validates :author_id, presence: true
    validates :book_id, presence: true
end

架构的相关部分

  create_table "authors", force: true do |t|
    t.string   "last_name"
    t.string   "first_name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "contributions", force: true do |t|
    t.integer  "book_id"
    t.integer  "author_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "books", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "year_of_publication"
    t.string   "description"
  end

我在BooksController中的 new 创建操作

def new
@book = Book.new

# Displays empty fields in the new book action view (n.times)
1.times { @book.authors.build }
1.times { @book.book_images.build }
@book.stock_items.build
end

def create

@book = Book.new(book_params)

if @book.save
  redirect_to @book
  flash[:success] = "Book added"
else
  render 'new'
  flash.now[:danger] = "Book NOT added"
end
end

我的book_params

私有

def book_params
  # Include the nested parameters in the strong parameters as model_name_attributes !!!!!!!!!!
  params.require(:book).permit( :name, 
                                :description, 
                                :year_of_publication, 
                                authors_attributes: [ :first_name, :last_name ], 
                                book_images_attributes: [ :image_url, :book_id ], 
                                libraries_attributes: [ :name ], 
                                stock_item_attributes: [ :book_id, :library_id ], 
                                contribution_attributes: [ :book_id, :author_id ])
end

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您应该使用 join_table contributions 。将 fields_for 部分更改为可以使其正常运行

<div class="panel panel-default">
        <div class="panel-body">
            <h3>Add authors</h3>
            <h4>Choose from existing authors</h4>
            <%= f.fields_for :contributions do |builder| %>
            <%= builder.collection_select(:author_id, Author.all, :id, :full_name, prompt: "Select from existing authors") %>
            <% end %>
        </div>
    </div>

答案 1 :(得分:0)

您能否显示您用于多对多关系的所有三个模型

class Physician < ActiveRecord::Base
attr_accessible :name, :title
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
 attr_accessible :details, :patient_id, :physician_id
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  attr_accessible :name , :details
  has_many :appointments
  has_many :physicians, through: :appointments
end

关系定义本身应该存在一些问题,这通常会立即起作用