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。