如何通过关系为has_many创建表单?

时间:2015-07-04 02:20:20

标签: ruby-on-rails ruby ruby-on-rails-4 has-many-through has-many

在我的应用程序中,我有一个书籍模型的书籍索引页面。把它想象成一个图书馆。

现在我有由列表组成的板。让我们说我有一个叫做类别的董事会。

所以我去了类别委员会。在我的网址是www.example.com/board/1

在这个类别板上有很多列表。可以说我有一个名为编程书籍的列表。

所以现在我需要在这个名为Programming Books的列表中添加书籍。

我有一切设置我只是不知道如何将书籍添加到列表中。当我点击添加书籍时如何获得list_id?我希望能够点击添加书籍然后转到列出所有书籍的页面。然后,我想通过检查每本书来选择书籍,然后将它们添加到列表中。

不要担心创建正确设置的列表或板卡我只是想将书籍添加到列表中。

类别主板(www.example.com/board/1)

===================     ===================     
=Programming Books=     =Adventure Books  =
===================     ===================
= Book 1          =     = add books       =
= Book 2          =     =                 =
= Book 3          =     =                 =
= add books       =     =                 =
===================     ===================

列表模型

belongs_to :user, inverse_of: :list

has_many :list_books
has_many :books, through: :list_books

accepts_nested_attributes_for :list_books, :allow_destroy => true

List_Books模型

belongs_to :list
belongs_to :books

预订模型

belongs_to :user, inverse_of: :books

has_many :list_books
has_many :lists, through: :list_books

accepts_nested_attributes_for :list_books, :allow_destroy => true

列出控制器

def addbooks
  // Not sure what to put here? It needs to grab the list_id from the list where i clicked add books.
end

private
  def_params
    // Not sure what params i need
  end

添加书籍视图

// i need of list of all the books here. Then i want to check each book i want and then submit.

1 个答案:

答案 0 :(得分:1)

您不需要在单独的操作中处理它,只需要定期创建操作并添加accept_nest_attributes,如本例所示

class Book < ActiveRecord::Base 
    has_many :classifications, :dependent => :destroy, :autosave => true , :inverse_of => :book accepts_nested_attributes_for :classifications, :allow_destroy => true, :reject_if => :all_blank 
    has_many :categories, :through => :classifications 
end


class Category < ActiveRecord::Base 
   has_many :classifications, :dependent => :destroy, :autosave => true , :inverse_of => :category accepts_nested_attributes_for :classifications, :allow_destroy => true, :reject_if => :all_blank 
  has_many :books, :through => :classifications 
end


class Classification < ActiveRecord::Base 
  belongs_to :category, :inverse_of => :classifications 
  belongs_to :book, :inverse_of => :classifications 
end

然后将其添加到您的视图中。

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

 <p>
 <%= f.label :name %>
 <%= f.text_field :name %>
 </p>

 <p>Categories</p>
 <ul>
 <% @categories.each do |cat| %>
 <%= hidden_field_tag "book_category_ids_none", nil, {:name => "book[category_ids][]"}%>
 <li>
 <%= check_box_tag "book_category_ids_#{cat.id}", cat.id, (f.object.categories.present? && f.object.categories.include?(cat.id)), {:name => "book[category_ids][]"} %>
 <%= label_tag "book_category_ids_#{cat.id}", cat.name %>
 </li>
 <% end %>
 </ul>

 <%= f.submit %>

<% end %>

检查完整示例here