【问题标题】:Why does create_association not work on a belongs_to association?为什么create_association 不适用于belongs_to 关联?
【发布时间】:2015-11-20 23:40:04
【问题描述】:

我有这个关联设置:

class Connection < ActiveRecord::Base
  belongs_to :membership
end

class Membership < ActiveRecord::Base
  has_many :connections, dependent: :destroy
end

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

@membership ||= Membership.find_or_create_by(member: @member)
@connection ||= @membership.create_connection!(sent_at: Time.now, times_sent: 1, request_status: 0)

我收到此错误:

undefined method `create_connection!' for #<Membership:0x007fab2dac83b8>

尽管Rails API docs 说我应该能够做到这一点:

belongs_to(name, scope = nil, options = {}) Link

Methods will be added for retrieval and query for a single associated object, for which this object holds an id:

association is a placeholder for the symbol passed as the name argument, so belongs_to :author would add among others author.nil?.

create_association(attributes = {})
Returns a new object of the associated type that has been instantiated with attributes, linked to this object through a foreign key, and that has already been saved (if it passed the validation).

create_association!(attributes = {})
Does the same as create_association, but raises ActiveRecord::RecordInvalid if the record is invalid.

这可能是什么原因造成的?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord


    【解决方案1】:

    我认为你们的关系有些混乱。您已链接 belongs_to 的文档。由于连接属于会员,您可以

    @membership ||= @connection.create_membership(attr1: val1, attr2: val2)
    

    但是,成员资格不属于连接。会员有许多联系。向下滚动到has_many,可以看到要建立关联,需要使用:

    collection.create(attributes = {}, …)
    

    将其应用于您的用例,您会得到

    @connection || = @member.connections.create(sent_at: Time.now, times_sent: 1, request_status: 0)
    

    【讨论】:

    • 没问题!很高兴为您提供帮助
    【解决方案2】:

    我想通了,Rails 4 文档似乎已经过时了。

    我应该做的是:

    @membership.connections.create!(sent_at: Time.now, times_sent: 1, request_status: 0)
    

    这对我有用。

    【讨论】:

    • 文档并没有过时(嗯,它们很可能是,但在这种情况下它们不是),你只是把事情搞混了一点。查看my answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多