1

在我的应用程序中,我有一个书籍模型书籍的索引页面。把它想象成一个图书馆。如何通过关系为has_many创建表单?

现在我有董事会组成的名单。可以说我有一个叫做Categories的板子。

所以我去分类板。在我的网址是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 

Book模型

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 

AddBooks查看

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

回答

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

+0

这实际上是行不通的,你看,我有一个由列出的许多董事会。就像一个董事会可能被称为行动书与子类型的名单。然后另一个董事会可能被称为教科书与子类型的名单。我需要获取list_id并以这种方式添加书籍。有点像音乐库和播放列表,如何将歌曲从库中添加到播放列表中。这些列表就像播放列表,书是图书馆。 – EliteViper7777