joker1007 / activemodel-associations

has_many and belongs_to macro for Plain Ruby Object.
MIT License
79 stars 27 forks source link

NoMethod error on accessor for id for belongs_to association #7

Closed TechRsch closed 9 years ago

TechRsch commented 9 years ago

I'm trying to use activemodel-associations to create a series of associations to build a query. However, it appears that it's not building the expected methods, or at least those I expect..

The code is basically:

class YmmYear < ActiveRecord::Base
  validates :year, presence: true
  def name
    self.year
  end
end
class Ymm
  include ActiveModel::Model
  include ActiveModel::Associations
  attr_accessor :ymm
  belongs_to :ymm_year
  def [](attr)
    self.send(attr)
  end
  def []=(attr, value)
    self.send("#{attr}=", value)
  end
end
class Admin::YmmsController < ApplicationController
  before_action :check_if_admin
  def new
    @ymm = Ymm.new
    @ymm.ymm_year_id = 1126
  end
end

The assignment to @ymm.ymm_year_id fails with NoMethod error.

undefined method `ymm_year_id=' for #<Ymm:0x9c549d8 @association_cache={}>

The methods to which @ymm responds that include "ymm_year" are:

autosave_associated_records_for_ymm_year
ymm_year
ymm_year=
build_ymm_year
create_ymm_year
create_ymm_year!

A classic ActiveRecord belongs_to assocation would create the accessor ymm_year_id, would it not? Or, am I misunderstanding this?

Thanks.

TechRsch commented 9 years ago

When I update the model to add this line, the Rails form helpers begin to work:

  attr_accessor :ymm, :ymm_year_id
joker1007 commented 9 years ago

Yes, Your way is right. belongs_to needs foreign key attribute.