Attribute references in models with sort_to relationships through a nested namespace

Okay, so I thought I understood how relationship specifications work on rails, but I struggled with this for a day.

In some context, I have two models: "Cars and model names" (for example, Impala, Charger, etc.), where Cars are instances of model names, and model names are nothing more than a model name lookup table and some other levels of the attribute model. The model name controller is nested in the admin namespace, since only administrators can use CRUD model names. End users can add vehicle instances to the Cars model.

So in routes.rb I have:

  resources :cars

  namespace :admin do resources :model_names end

The model is defined as:

class Admin::ModelName < ActiveRecord::Base
end
class Car < ActiveRecord::Base
  belongs_to :admin_model_name
end

Migrations:

class CreateCars < ActiveRecord::Migration
  def self.up
    create_table :cars do |t|
      t.string :chassis_number
      t.string :description
      t.references :admin_model_name
      t.timestamps
   end
end

class CreateAdminModelNames < ActiveRecord::Migration
  def self.up
    create_table :admin_model_names do |t|
      t.string :model
      t.integer :sort_index
      #...additional attributes removed
      t.timestamps
    end

CRUD ModelName . . , , :

<%= @car.admin_model_names.Model =>

:

undefined method `admin_model_names' for #<Car:0x000001040e2478>

attr_accessible ModelNames, . . HABTMT Cars Users, , . . ?

, , :

 <%= Admin::ModelName.find(@car.admin_model_name_id).model %>

( ), . Rails?

.

+5
2

:

class Car < ActiveRecord::Base   
  belongs_to :admin_model_name, :class_name => "Admin::ModelName" 
end

http://guides.rubyonrails.org/association_basics.html

3.4?

:foreign_key => "admin_model_name_id"
, .

, .

+9

class Car < ActiveRecord::Base
  belongs_to :admin_model_name, :class_name => 'Admin::ModelName'
end

: foreign_key = > '' .

+2

All Articles