0

NB. Actually, this code works fine, I just has a bug in my routes. I'll leave the question here in case it's of use to someone...

I'm not sure how to access the results of a search within Mojolicious templates

For example, I've tried this, which doesn't work:

sub list {
   my $self= shift;
   #Return a list of questions
   my @list = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }});
   $self->stash(list => \@list);
}

Then in my template is

% for my $item (@$list) {
  <%= $item->question %> 
  <%= $item->explanation %> <br />
% }

However this gives the error

Not an ARRAY reference at template line x (where line x is the line containing @$list)

i've tried a variety of other things.
If I call search in list context and dump the results, I can see I get a list of 'Schema::Result::Question' objects - that's right.

I'm just not sure how to loop through and access the data in the template?

mark
  • 1,769
  • 3
  • 19
  • 38

1 Answers1

0
$self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }})

returns a resultset.

You can call ->all on it like so ( you missed the ->all )

my @list = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }})->all;

OR, you can iterate through the resultset like so :

my $rs = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }});
while ( my $question = $rs->next ){
# do things with $question
}

This does not immediately fetch all those questions, but, as it is a resultset, it only executes when called upon ( i.e. you start the iteration ).

This may be an advantage to the second method.

bytepusher
  • 1,568
  • 10
  • 19
  • please let me know if this answers your question, you should call ->all to get a list, I am sure, but the error message does not quite fit for me, perhaps there is another problem... – bytepusher Nov 30 '14 at 23:44
  • thanks for the input, no, adding ->all generates the same result from ->search as without. The problem seems to be that mojolicious doesn't like being parsed a list of blessed objects (which is what's in list). – mark Dec 01 '14 at 08:06
  • actually, that's not it either. I mapped the specific results to an array of hashes (my @result = map { {question => $_->question, explanation => $_->explanation} } @list;) and sent that, which still fails with the same error. – mark Dec 01 '14 at 09:13
  • Doh, i had a straight bug in my code dealing with the routes so I wasn't actually dereferencing @$list at all, and therefore it wasn't a hash. Perhaps the code will make a useful example to someone... – mark Dec 01 '14 at 09:43
  • I found I can do <%= Dumper($list); use Data::Dumper %> in my templates, which works fine. Very useful – mark Dec 01 '14 at 09:52
  • sorry for not getting back, lately, I have had issues reaching stackoverflow at times ( quite erratic ). Glad you solved it, sorry I wasn't much help ;) – bytepusher Dec 01 '14 at 12:50