0

I'm interested in creating and updating a row in table without a primary key. My table has 3 columns - person_id, year and salary. I understand that I should use has_and_belongs_to but I'm having problems understanding how to implement my create and update methods and my form.html file. Can anyone help explain this to me, perhaps with a simple example of how to do it?

user1107922
  • 610
  • 1
  • 12
  • 25
  • checkout http://stackoverflow.com/questions/5120703/creating-a-many-to-many-relationship-in-rails-3 – Prasad Surase Oct 03 '12 at 08:35
  • (person_id, year) seems like a natural primary key, but Rails doesn't support composite keys. You can try this gem however: http://compositekeys.rubyforge.org/ – Teoulas Oct 03 '12 at 08:59

2 Answers2

0

has_and_belongs_to_many example

# 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

join table look like

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

now you can accessing your information

$ User.categories
$ Category.users
$ user = User.first
$ user.categories
$ category = Category.first
$ category.users
Dipak Panchal
  • 5,996
  • 4
  • 32
  • 68
0

Add a primary key, and ignore it. You can add a unique index on (person_id, year) to simulate a PK constraint, but ActiveRecord heavily relies on having ids for its instances.

rewritten
  • 16,280
  • 2
  • 47
  • 50