how can I write this is rails (for loop)

I want to write this in rails:

@aux= @rep_tickets.rp_parts.size

for i=0, i< @aux, i++     @rep.ticket.price=@rep.ticket.price + @rep_tickets.rp_part[i].price end

John Smith wrote:

I want to write this in rails:

@aux= @rep_tickets.rp_parts.size

for i=0, i< @aux, i++     @rep.ticket.price=@rep.ticket.price + @rep_tickets.rp_part[i].price end    @rep.ticket.price = @rep_tickets..rp_parts.map(:&price).sum

Russell McConnachie wrote:

John Smith wrote:

I want to write this in rails:

@aux= @rep_tickets.rp_parts.size

for i=0, i< @aux, i++     @rep.ticket.price=@rep.ticket.price + @rep_tickets.rp_part[i].price end    @rep.ticket.price = @rep_tickets..rp_parts.map(:&price).sum

Wow, fat fingered that.

@rep.ticket.price = @rep_tickets.rp_parts.map(&:price).sum

Russell McConnachie wrote:

Russell McConnachie wrote:

@rep.ticket.price = @rep_tickets..rp_parts.map(:&price).sum

Wow, fat fingered that.

@rep.ticket.price = @rep_tickets.rp_parts.map(&:price).sum

Doesn't seem to work:

@repair_ticket.total_price = @repair_ticket.rp_parts.map(:&price).sum

SyntaxError: compile error (irb):71: syntax error, unexpected tIDENTIFIER, expecting ')' @repair_ticket.total_price = @repair_ticket.rp_parts.map(:&price).sum

John Smith wrote:

I want to write this in rails:

@aux= @rep_tickets.rp_parts.size

for i=0, i< @aux, i++    @rep.ticket.price=@rep.ticket.price +
@rep_tickets.rp_part[i].price end

@rep.ticket.price = @rep_tickets..rp_parts.map(:&price).sum

or even @rep_tickets.rp_parts.sum(:&price)

(consider also @rep_tickets.rp_parts.target.sum(:&price) The difference between the two is that the first will always hit the
database (ie it will do select sum(price) from ...) whereas the second
won't if rp_parts has already been loaded (assuming rp_parts is an
active record association)

Fred

Frederick Cheung wrote:

.map(&:price)

Note that & causes the following object, if not already a Proc, to be sent a .to_proc method. Rails defines Symbol#to_proc. Your syntax error is because you have transposed the & and : in the line.

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com