0

我有興趣創建和更新表中沒有主鍵的行。我的表格有3列 - person_id,年份和薪水。我明白我應該使用has_and_belongs_to,但我在理解如何實現我的創建和更新方法以及我的form.html文件時遇到問題。任何人都可以幫助解釋這一點,也許有一個簡單的例子來說明如何做到這一點?Rails多對多更新並創建

+0

checkout http://stackoverflow.com/questions/5120703/creating-a-many-to-many-relationship-in-rails-3 –

+0

(person_id,year)看起來像是一個自然的主鍵,但Rails沒有'不支持複合鍵。你可以試試這個寶石:http://compositekeys.rubyforge.org/ – Teoulas

回答

0

has_and_belongs_to_many例如

# category model 
class Category < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

# user model 
class User < ACtiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

連接表的樣子

class CreateCategoriesUsersJoinTable < ACtiveRecord::Migration 
    def change 
    create_table :categories_users, :id => false do |t| 
     t.integer :category_id 
     t.integer :user_id 
    end 
    end 
end 

現在你可以訪問你的信息

$ User.categories 
$ Category.users 
$ user = User.first 
$ user.categories 
$ category = Category.first 
$ category.users 
0

添加一個主鍵,將其忽略。您可以在(person_id,year)上添加一個唯一索引來模擬PK約束,但ActiveRecord嚴重依賴其實例的ID。