views:

37

answers:

3

I want to create a model 'Relation' which extends ActiveRecord::Base, set it's table name as 'questions_tags', and without primary key. What should I do?

class Relation < ActiveRecord::Base
  set_table_name 'questions_tags' # set table name, right?

  # how to define 'no-pk'?

end

UPDATE


Hi, guys. I know use 'create_table' can solve this problem, but this is just what I want to know: What is the magic behind create_table(:id=>false)? How can I get the same effect without using create_table(:id=>false)?

A: 

If you're looking to create a pivot table, as it looks like from the table name, then AR will handle that in the background.

However, if you're looking to create a table with more feilds then: 1) rename your table to "realtions" please 2) use a primary key "id"

There's no good reason not to be using a primary key in a table, and it is very likely that you might well find yourself regretting it later.

thomasfedb
@thomasfedb, thanks. Please see my updated question, I just want to know what had happened behind.
Freewind
A: 

Why don't you want a PK?

Active Record expects a PK, and I don't see what harm it can do.

DanSingerman
@Dan, thanks. Because it is a join table, I don't want it have a PK
Freewind
+1  A: 

Create a migration that looks like this:

class CreateQuestionsTags < ActiveRecord::Migration

  def self.up
   create_table :questions_tags, {:id => false, :force => true} do |t|
     ...
     t.timestamps
   end
  end

  def self.down
   drop_table :questions_tags
  end

end
auralbee
@auralbee, thanks for your answer. Please see my updated question
Freewind