开发者

Where Do I Put the Scope for Related Models/Controllers

开发者 https://www.devze.com 2023-03-11 01:51 出处:网络
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|.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号