[英]get associated model from rails model?
在保存Payment
模型之前,我想為其他模型Post
設置屬性。
我的付款belongs_to :user
,我的用戶具有has_many :posts
和has_many :payments
在我的payment.rb中,有一個before_create :set_expiration_date
回調。
如何設置我的帖子模型的到期日期?
是這樣嗎
def set_expiration_date
self.User.Post.last.expiration = Date.today + self.duration.days
end
由於付款尚未保存在數據庫中並因此與User
關聯,因此before_create甚至可以工作嗎?
如果我關心一對一關聯的Payment-Post,這會很簡單嗎?
我通過以下方式保存付款記錄:
#Payment.rb
def save_with_payment
if valid?
Stripe::Charge.create(
:amount => 3000,
:currency => "usd",
:card => stripe_card_token,
:description => "Charge for test@example.com")
end
save!
end
支付模型確實具有user_id屬性,但似乎始終為零
SQL (1.1ms) INSERT INTO "payments" ("amount", "created_at", "transaction_number", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["amount", nil], ["created_at", Sun, 23 Feb 2014 14:50:42 UTC +00:00], ["transaction_number", nil], ["updated_at", Sun, 23 Feb 2014 14:50:42 UTC +00:00], ["user_id", nil]]
謝謝
post = self.user.posts.last
post.expiration = Date.today + self.duration.days
post.save!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.