一对一关系中的Rails分配

时间:2015-07-26 22:07:41

标签: ruby-on-rails

好吧,所以我试图通过一对一的关系将Profile对象连接到Session对象。我理解的方式是如果我正确设置了关系,以下是相同的(如果我错了请纠正我)

@my_session << @my_profile

@my_session.profile = @my_profile

@my_session.profile_id = @my_profile.id

我在模型文件夹中设置了以下内容

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' 

在我的数据库表中,session中有profile_id

在我的rails控制台中执行以下两个命令可以正常工作:

@my_session.profile = @my_profile

@my_session.profile_id = @my_profile.id

但是,每当我尝试执行以下操作时:

@my_session << @my_profile

我收到错误

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'

这对我的导轨安装方式有什么问题吗?任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:1)

在ActiveRecord模型上声明has_one关联时,它会获得以下方法:

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

其中不包括铲运算符<<因此您的错误<<在这种情况下未定义。这不是配置问题。看起来你的配置工作正常。这是Rails指南中的具体细节

http://guides.rubyonrails.org/association_basics.html#has-one-association-reference

在模型中包含<<has_many时,has_and_belongs_to_many铲运算符与所有其他方法一起定义:

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 = {})

以下是详细信息:

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