belongs_to not working in rails 4.0

I'm building a small example with rails 4.0. There are something strange when I create a one-many relation between 2 models. A Cluster has_many :request and A request belongs_to :cluster.

class Cluster < ActiveRecord::Base
    has_many :requests
    paginates_per 10
end

class Request < ActiveRecord::Base
    paginates_per 10
    belongs_to :cluster, :class_name => "Cluster"
end

Then when I create a cluster and insert with some request I get an error

def do_cluster
    requests = Request.where(:state => 'new').limit(4)
    cluster = Cluster.new()
    cluster.state = "new"
    requests.each do |request|
      cluster.requests << request
      puts "abc"
      request.state = "clustered"
    end
    cluster.save
    redirect_to "index"
  end

=> Completed 500 Internal Server Error in 16ms (ActiveRecord: 1.0ms)

ActiveModel::MissingAttributeError (can't write unknown attribute cluster_id): app/controllers/admin_controller.rb:21:in `do_cluster'.

I don't understand what wrong I made. Can anyone help?

Upvotes: 0

Views: 435

Answers (1)

Thinh D. Bui
Thinh D. Bui

Reputation: 76

The problem you need to know that although ActiveRecord and your table on database is connected via convention in Rails, it doesn't mean Association in your model will create a link (foreign key, or even column) in your database.

In your case, you need a column named cluster_id in table 'requests' while you're creating table 'requests'

Model

class Cluster < ActiveRecord::Base
    has_many :requests
    paginates_per 10
end

class Request < ActiveRecord::Base
    paginates_per 10
    belongs_to :cluster
end

Migration

class CreateRequests < ActiveRecord::Migration
  def change
    create_table :requests do |t|
      # any fields
      t.integer :cluster_id

      t.timestamps
    end
  end
end

Upvotes: 3

Related Questions