简体   繁体   中英

get associated model from rails model?

Before saving my Payment model I would like to set an attribute for my other model Post .

My Payment belongs_to :user and my User has has_many :posts and has_many :payments

In my payment.rb I have an before_create :set_expiration_date callback.

How can I set the expiration date of my Post Model?

Is it something like this?

def set_expiration_date
    self.User.Post.last.expiration =  Date.today + self.duration.days
end

Would the before_create create even work since the payment has not been saved in the database yet and hence the association with the User ?

Would it be simple if I care a 1-to-1 association Payment-Post?

I save my payment record the following way:

#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

The payment model does have a user_id attribute but it seems to always nil

  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]]

Thank you

post = self.user.posts.last
post.expiration =  Date.today + self.duration.days
post.save!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM