Here is my scenario:
I have three models Subscriber, Subscription, Plan
, with has_many :through
relationship
between Subscriber and Plans.
A subscriber can have multiple plans with one active plan. Whenever a subscriber selects a plan I save it using accepts_nested_attributes_for :subscriptions
. I get one plan from the form.
Now my problem is I want to get the ID of t开发者_Go百科he record created in subscriptions table.
Currently I am retrieving it by finding all subscriptions for the subscriber ordered descending on date created and taking first from the resultset. Is there any direct method to do this?
Suppose you have this in controller:
@subscriber = Subscriber.find(params[:id])
@subscriber.update_attributes(params[:subscriber])
then you can find last subscription id with:
@subscriber.subscriptions.order("created_at DESC").first.id
@subscriber.subscriptions.last
is a cheaper solution. otherwise you could write a custom method in your model.
精彩评论