2011-03-21 94 views
14

是否有任何教程外面如何腳手架使用許多一對多的關係,一個簡單的模型?軌道3腳手架關係模型的

+1

使用谷歌搜索給我這個:http://jrhicks.net/Projects/rails/has_many_and_belongs_to_many.pdf,我希望你可以使用 – rsplak 2011-03-21 21:54:46

+0

這是5.5年前寫的!我懷疑它在Rails 3中有效。 – 2011-03-21 21:57:48

+0

你到底在找什麼?多對多的顯示會變得棘手。我認爲生成一些東西並不可行。 – 2011-03-21 22:01:18

回答

45

這嘖我已經在使用紅寶石1.9.2 on Rails的3.0.5產生由步驟下面的步驟testapp寫入。另請參閱我使用的寶石的「Gemfile」(整個Testapp可下載,鏈接在第15部分末尾)。所以這裏有雲:

1)去,你要創建一個測試應用程序的地方,然後

rails new mynewtestapp 
cd mynewtestapp 

2)再加入2個模型有has_and_belongs_to_many協會

rails g scaffold book title:string author:string 
rails g scaffold user name:string age:integer 

3 ),那麼你需要創建的連接表爲asssociation ...默認情況下軌將尋找由名字都以字母順序相關的表的名稱的表...所以讓我們創建一個遷移來建立這樣一個表

rails g migration createBooksUsers 

4)打開生成的遷移文件,該文件在這一點上看起來像

class CreateBooksUsers < ActiveRecord::Migration 
    def self.up 
    end 

    def self.down 
    end 
end 

5)修改成這樣

class CreateBooksUsers < ActiveRecord::Migration 
    def self.up 
    create_table :books_users, :id => false do |t| 
     t.integer :book_id 
     t.integer :user_id 
    end 
    end 

    def self.down 
    drop_table :books_users 
    end 
end 

6)has_and_belongs_to_many協會加入書和用戶模型,以及由關係添加的新ID。

app/model/book.rb

class Book < ActiveRecord::Base 
    attr_accessible :title, :author, :user_ids 
    has_and_belongs_to_many :users 
end 

應用程序/模型/ user.rb

class User < ActiveRecord::Base 
    attr_accessible: :name, :age, :book_ids 
    has_and_belongs_to_many :books 
end 

7)現在我們的模型和遷移完成後...可以創建表

rake db:create 
rake db:migrate 

(以及創建可能不是必要的,如果您使用sqlite3的,或者如果你已經創建了數據庫手動使用,這個例子將工作使用SQLite therfore我還沒有添加與安裝一個數據庫管理系統什麼。但是,因爲有很多,實際上都是值得足夠用來被很好的記錄,你會發現有關的任何幫助相當快)

8)現在決定哪個對象應包括哪些物件當然被分配....你可以這樣做兩種方式...我會保持它的簡單,並證明了一個......可以說你只有幾個用戶和要指派那些書......

在這一點上,我會說讓我們得到一些外部的幫助,如二進制x建議...但爲了簡單起見,我會選擇simple_form gem over Formtastic。我想每個人都有自己的最愛......但simple_form似乎給你在CSS-造型整體輸出到您的願望更加自由......所以讓我們在這一點上安裝simple_form,只是做

echo "gem 'simple_form', :git => 'git://github.com/plataformatec/simple_form.git'" >> Gemfile 

添加simple_form您的Gemfile,然後運行

bundle install 

並安裝簡單的表格,你的應用程序(即通過

rails g simple_form:install 

9)時產生的配置,默認樣式和語言文件)來修改我們的圖書形成

書形成,現在應該是這樣的

應用程序/視圖/書籍/ _form。 html.erb

01 <%= form_for(@book) do |f| %> 
02  <% if @book.errors.any? %> 
03  <div id="error_explanation"> 
04   <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2> 
05  
06   <ul> 
07   <% @book.errors.full_messages.each do |msg| %> 
08   <li><%= msg %></li> 
09   <% end %> 
10   </ul> 
11  </div> 
12  <% end %> 
13  
14  <div class="field"> 
15  <%= f.label :title %><br /> 
16  <%= f.text_field :title %> 
17  </div> 
18  <div class="field"> 
19  <%= f.label :author %><br /> 
20  <%= f.text_field :author %> 
21  </div> 
22  <div class="actions"> 
23  <%= f.submit %> 
24  </div> 
25 <% end %> 

使用simple_form,我們只需更換一些上面的代碼(線1和14 - 24),所以整個文件應該是這樣的:

01 <%= simple_form_for(@book) do |f| %> 
02  <% if @book.errors.any? %> 
03  <div id="error_explanation"> 
04   <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2> 
05  
06   <ul> 
07   <% @book.errors.full_messages.each do |msg| %> 
08   <li><%= msg %></li> 
09   <% end %> 
10   </ul> 
11  </div> 
12  <% end %> 
13  
14  <%= f.input :title %> 
15  <%= f.input :author %> 
16  <%= f.association :users %> 
17  
18  <%= f.button :submit %> 
19  
20 <% end %> 

10)現在,你可能要啓動應用程序

rails s 

添加一些用戶,然後再添加一本書,並有你的第一個has_and_belongs_to_many形式: first simple_form form without special effects

11)嗯,這可能還不是最漂亮的東西看看,但簡單的添加樣式表將有助於一點...創建一個新文件

public/stylesheets/simple_form.css 

並粘貼以下行到它

/* public/stylesheets/simple_form.css */ 
.simple_form label { 
    float: left; 
    width: 100px; 
    text-align: right; 
    margin: 2px 10px; 
} 

.simple_form div.input { 
    margin-bottom: 10px; 
} 

.simple_form div.boolean, .simple_form input[type='submit'] { 
    margin-left: 120px; 
} 

.simple_form div.boolean label, .simple_form label.collection_radio, .simple_form label.collection_check_boxes{ 
    float: none; 
    margin: 0; 
} 

.simple_form .error { 
    clear: left; 
    margin-left: 120px; 
    font-size: 12px; 
    color: #D00; 
    display: block; 
} 

.simple_form .hint { 
    clear: left; 
    margin-left: 120px; 
    font-size: 12px; 
    color: #555; 
    display: block; 
    font-style: italic; 
} 

然後重新加載頁面和... ... Tadaa第一擊...... after adding a default simple_form stylesheet

12),如果你不喜歡多-choice,列表框只是回到書本形成

應用程序/視圖/書籍/ _form.html.erb

和修改線

15  <%= f.input :author %> 

稍微

15  <%= f.input :author, :as => :check_boxes %> 

進行檢查盒出列表框的....但... EWWW ....看看這個: left to right checkbox display

13)有些東西似乎有點不對......從左至右的選項已知會偶爾麻煩simple_form greenhorns,但實際上它的一個易於修復的問題

並且在這個小格式問題之上,你也可能想要 看到他背後的大括號名用戶的年齡,像「湯姆(25)」

...所以讓我們做3個權宜之計

一)取消註釋並設置在配置/初始化/ simple_form.rb 2個選項爲了包裝每個複選框有一個div和複選框集放在一個字段內

# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. 
    config.collection_wrapper_tag = :fieldset 

    # You can wrap each item in a collection of radio/check boxes with a tag, defaulting to none. 
    config.item_wrapper_tag = :div 

二)修改我們的simple_form.css樣式表一點,如添加:

fieldset { border: 0; } 

...除非你更喜歡圍繞字段集的一個很大的醜陋邊界

c)在我們的用戶模型中創建方法'to_label',因爲默認情況下'to_label'是第一個方法simple_form尋找以獲得一個String-表示來顯示對象。通過一個奇怪的事件我們的模型用戶有一個名爲「名稱」的列。名稱也是simple_form在模型中查找的一種方法,我們很幸運,此應用程序迄今爲止已運行良好。如果我們已經調用了名字列forename,那麼Rails不會列出用戶名,而是列出默認的ruby對象表示(例如<#User:521369846>)。我想我們是幸運;-)

應用程序/模型/ user.rb

class User < ActiveRecord::Base 
    has_and_belongs_to_many :users 

    def to_label 
    "#{name} (#{age})" 
    end 

end 

和編輯的形式得到一個漂亮的外觀... nice and cozy edit view

14)現在只有放映視圖需要顯示書的業主......那不是太硬或者,只需打開顯示視圖

應用程序/視圖/書籍/ show.html.erb

,並添加利內斯13-16顯示bookowners:

01 <p id="notice"><%= notice %></p> 
02  
03 <p> 
04  <b>Title:</b> 
05  <%= @book.title %> 
06 </p> 
07  
08 <p> 
09  <b>Author:</b> 
10  <%= @book.author %> 
11 </p> 
12  
13 <p> 
14  <b>Who owns a copy?</b> 
15  <%= @book.users.map {|x| x.to_label}.join ', ' %> 
16 </p> 
17  
18 <%= link_to 'Edit', edit_book_path(@book) %> | 
19 <%= link_to 'Back', books_path %> 

和最後但並非最不重要......演出視圖 Who owns a book?

15)好了,這麼多的快速教程,以HABTM或文字has_and_belongs_to_many協會在軌道中。我已經把我的測試應用程序,而在 寫這個網上,我創建https://1drv.ms/u/s!Alpu50oGtUZq7AiJkL08QqBiMAjb

+0

寫得很好!相當徹底。 – Andrew 2012-04-10 18:58:00

+0

這在軌道3.2.3中仍然有效嗎?我覺得我已經正確地執行了步驟,但在步驟11(試圖創建書籍時)顯示「無法批量分配受保護的屬性」時出現錯誤。如果我只是做錯了,請忽略。 :) – timfreilly 2012-05-07 23:13:46

+0

@timfreilly:我還沒有試過這個在rails 3.2.3上,但作爲「一切都是新的」,我。即Rails和Simple-Form,我猜想幾件事實際上是不同的。可悲的是我沒有機會使用Rails 3.1+,所以我不能說。試着谷歌你提到的錯誤消息,我相信你會找到一個解決方案的領導。 – Ingo 2012-05-20 11:53:08