【发布时间】: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