سؤال

I have a model classed

PaypalTransactionResponse(id: integer, paypal_transaction_id: uuid, response: text, created_at: datetime, updated_at: datetime)

class PaypalTransaction < ActiveRecord::Base
    has_many :responses, class_name: "PaypalTransactionResponse", dependent: :destroy
    belongs_to :response, class_name: "PaypalTransactionResponse", foreign_key: "response"
..
end

class PaypalTransactionResponse < ActiveRecord::Base
    has_one :paypal_transaction
    belongs_to :paypal_transaction
..
end

on Rails 4.0.5 the following code works fine. on Rails 4.1.1 it doesn't

p = PaypalTransaction.first
p.responses.create(response: "some response text")

pry(#<PaypalTransaction>)> p.responses.create(response: "some response text")
  SQL (0.4ms)  INSERT INTO "paypal_transaction_responses" ("created_at", "paypal_transaction_id", "response", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", "2014-05-10 13:54:37.512642"], ["paypal_transaction_id", "048267d9-2d47-4f0b-bc67-e206e296179d"], ["response", "some response text"], ["updated_at", "2014-05-10 13:54:37.512642"]]
ActiveModel::MissingAttributeError: can't write unknown attribute `paypal_transaction_response_id'
from /Users/me/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.1/lib/active_record/attribute_methods/write.rb:72:in `write_attribute'

Furthermore, I don't have a paypal_transaction_response_id attribute.. I guess there is some bad magic going on here, since it tries to guess some attribute that doesn't exist.

I didn't find any change in the Rails 4.1 changelog that could hint on this issue..

What can I do?

هل كانت مفيدة؟

المحلول

Your has_one :paypal_transaction association is most likely the cause of the problem.

It is expecting that there is a foreign key attribute on your PaypalTransaction class pointing to the PaypalTransactionResponse and it is guessing that this attribute is called paypal_transaction_response_id.

If you define your has_one like:

has_one :paypal_transaction, foreign_key: "response"

Then that should, hopefully, solve the problem.

The reason why it now fails in rails 4.1 is that writing of arbitrary attributes is no longer supported (you can't do my_obj[:my_att] = 42). I suspect that the code was no erroring in 4.0.5 but maybe wasn't working entirely as you'd expect - or at least you were getting away with it not working correctly.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top