Sander de Jong
Sander de Jong

Reputation: 75

How do I insert a record in Rails when there's no model and without using SQL

I have created a table that implements an n-to-n relation using the following statement:

create_table :capabilities_roles, :id => false do |t|
  t.integer :capability_id, :null => false
  t.integer :role_id, :null => false
end

There is no model for this table. How do I insert records without resorting to SQL?

I found this in the ActiveRecord::ConnectionAdapters::DatabaseStatements module:

insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)

and also:

insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])

I have no idea what arel means. Can someone give me an example of a valid insert? I would like to use stuff like :role_id => Role.find_by_name('Business user') in it.

Upvotes: 0

Views: 1839

Answers (3)

abonec
abonec

Reputation: 1421

In our project we have many meta tables which don't have models. To generate active record models on the fly we use follow module:

module EntityModel
  module_function
  ACCESS_MODELS = {}

  def for(table_name)
    return ACCESS_MODELS[table_name] if ACCESS_MODELS.has_key?(table_name.id)
    ACCESS_MODELS[table_name] = create_access_model(table_name)
  end

  def create_access_model(table_name)
    Class.new(ActiveRecord::Base) do
      self.table_name = table_name
    end
  end
end

This create anonymous models and store it in the global hash for performance purposes.

Uses as:

EntityModel.for(:users)

Upvotes: 0

Michał Szajbe
Michał Szajbe

Reputation: 9002

It looks like a join table for has and belongs to many relationship between Capability and Role models. You should let the Rails handle it for you. First define required associations:

class Capability < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :capabilities
end

Then just add instance of Role model to roles array of an instance of Capability model (or vice versa):

capability.roles << role
role.capabilities << capability

Removing records from join table is done via removing object from an array:

capability.roles -= [role]

Upvotes: 1

Mark Tabler
Mark Tabler

Reputation: 1429

If you're going to be manipulating the database records via Rails, then there should be a model for it. Just create a role.rb in your models directory with the lines

class Role < ActiveRecord::Base 
end

And you're as good as gold.

Upvotes: 1

Related Questions