Where Do I Put the Scope for Related Models/Controllers
Transaction
belongs_to Cart
and Cart
has_many Transactions
. I have a Cart
view that has the following in it: @cart.transactions.each do |t|
.
I want to limit the number of Transactions
in开发者_StackOverflowcluded in this loop to the first one. I also want to do this with a scope :first, limit(1).order('created_at ASC')
.
My question is: Where does this scope go (ie. in the Transaction model or Cart model) and how is it properly implemented?
I tried putting it in the Transactions
model and using this in the Cart
controller and it didn't work: @ftransaction = Cart.transaction.first
but that didn't work.
If you want the first transaction, you can call it like so:
@ftransaction = @cart.transactions.first
Notice the plural transactions. The order for this by default is id ASC
(unless you have a default scope defined), which should be for the sake of argument the same as created_at ASC
.
If you do decided you want or need the order as well as the limit, the scope would be defined in transaction.rb
.
Ah, I tried this and it worked:
@ftransaction = @cart.transactions.first
精彩评论