Reputation: 631
Alright, so I'm trying to connect a Profile object to a Session object through a one to one relationship. The way I understand it is if I have the relationship set up properly, the following is equivalent (please correct me if I'm wrong)
@my_session << @my_profile
@my_session.profile = @my_profile
@my_session.profile_id = @my_profile.id
I have the following set up in my models folder
profile.rb:
class Profile < ActiveRecord::Base
has_one :session
session.rb:
class Session < ActiveRecord::Base
# I tried this without foreign_key also, it works the same
belongs_to :profile, :foreign_key => 'profile_id'
And in my database tables, session has profile_id in it
Doing the following two commands in my rails console works fine:
@my_session.profile = @my_profile
@my_session.profile_id = @my_profile.id
However, whenever I try to do the following:
@my_session << @my_profile
I get an error
NoMethodError: undefined method `<<' for #<Session:0x00000004a26198>
from /.../rubies/ruby-2.2.2/lib/ruby/gems/2.2.0/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433:in `method_missing'
Is this some sort of problem with how I have rails setup or something? Any help would be great. Thanks.
Upvotes: 1
Views: 529
Reputation: 768
When declaring a has_one
association on an ActiveRecord model it gains the following methods:
association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})
Which does not include the shovel operator <<
thus your error that <<
is undefined in this case. It's not a configuration problem. Looks like your config is working fine. Here's the Rails guide with the specific details
http://guides.rubyonrails.org/association_basics.html#has-one-association-reference
The <<
shovel operator is defined along with all these other methods when you include a has_many
or has_and_belongs_to_many
on a model:
collection(force_reload = false)
collection<<(object, ...)
collection.delete(object, ...)
collection.destroy(object, ...)
collection=(objects)
collection_singular_ids
collection_singular_ids=(ids)
collection.clear
collection.empty?
collection.size
collection.find(...)
collection.where(...)
collection.exists?(...)
collection.build(attributes = {}, ...)
collection.create(attributes = {})
collection.create!(attributes = {})
Here's the details:
http://guides.rubyonrails.org/association_basics.html#has-many-association-reference
http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference
Upvotes: 1