1

在我的 Rails 应用程序中,我使用 Braintree gem 创建订阅。不知不觉中,我还创建了一个订阅模型和控制器来管理我想在本地存储的订阅信息。在我的模型中,订阅可以属于用户。但是,您可以做的一些正常工作不起作用,例如 current_user.subscriptions.build()

但是由于某种原因,当有人帮助我时,他们能够使用

current_user.create_subscription

这个 create_subscription 方法在哪里定义?它是否以某种方式覆盖了 Rails 约定?

我注意到 Braintree gem 中有一个 subscription.rb 文件。Braintree定义的类和我的订阅模型有冲突吗?我知道我可能可以重命名我的订阅模型,但我很好奇冲突是什么。

4

1 回答 1

1

Your issue is that the subscription relation is has_one or belongs_to, rather than has_many. User would not have a subscriptions method in this case as the attached subscription would be singular. Review the API docs for how to manipulate these sorts of relations in AR.

From the manual on has_one:

The following methods for retrieval and query of a single associated object will be added:

association(force_reload = false)

Returns the associated object. nil is returned if none is found.

association=(associate)

Assigns the associate object, extracts the primary key, sets it as the foreign key, and saves the associate object.

build_association(attributes = {})

Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved. Note: This ONLY works if an association already exists. It will NOT work if the association is 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).

Braintree does have a Subscription class, but this is namespaced to Braintree:Subscription so it is not the issue.

于 2011-05-05T18:39:29.567 回答