Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a model without primary key in rails?

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


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)?

like image 855
Freewind Avatar asked Jun 21 '10 11:06

Freewind


People also ask

What is primary key and foreign key in rails?

primary_key defines the name of the database field to be used as primary key instead of the default id . foreign_key defines the name of the database field which keeps references to the primary key field of another model.

What is Object Relationship Model rails?

Object Relational Mapping (ORM): simplify the use of databases in applications. Use objects to hold database records. One class for each table in the database. Objects of the class correspond to rows in the table. Attributes of an object correspond to columns from the row.

What is a Ruby on Rails model?

A Rails Model is a Ruby class that can add database records (think of whole rows in an Excel table), find particular data you're looking for, update that data, or remove data. These common operations are referred to by the acronym CRUD--Create, Remove, Update, Destroy.


2 Answers

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
like image 129
auralbee Avatar answered Oct 05 '22 09:10

auralbee


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.

like image 20
thomasfedb Avatar answered Oct 05 '22 10:10

thomasfedb