为什么create_association不能用于belongs_to关联?

时间:2015-11-20 23:40:04

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

我有这个关联设置:

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.

导致这种情况的原因是什么?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

我明白了,似乎Rails 4文档已经过时了。

我应该做的是:

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

这对我有用。