im trying to use find_by_sql, i think its a very useful function, but im
having trouble using it.
Actually it is very rarely of use
in my outcomes table i have:
id status
1 pass
2 fail
3 pass
4 pass
in my controller im trying to set it like this:
@status = Outcome.find_by_sql "select status from outcomes where id = 1"
This would be better off as Outcome.find 1
and in my outcome view
<body>
<%= @status %>
<%= "#{@status}" %>
</body>
when viewing the outcome.rhtml
it just appears as '#'
ultimately i am not convinced the find_by_sql is working at all...?
it is working. It's just not what you think it is. @status is an array of Outcome objects. when you call to_s on an array (which is effectively what you're doing with the <%= ), arrays just call to_s on their contents and join them. to_s on activerecord objects gives you something like #<Customer:0x2146688> which is invalid html (browsers frequently ignore everything between the <>).
If you follow my suggestion and do @outcome = Outcome.find 1
then you could stick <%= h @outcome.status %> in your view (the h function escapes the text making it safe for html
thanks for your response, i tested your solution and it works fine. but
its not quite as easy as ive posted above, the row im searching for in
the outcomes table isnt always as row 1.
so hardcoding a value in the controller is a no no.
the outcomes table i am working with, looks more like this:
thanks for your response, i tested your solution and it works fine.
but
its not quite as easy as ive posted above, the row im searching for in
the outcomes table isnt always as row 1.
so hardcoding a value in the controller is a no no.
the outcomes table i am working with, looks more like this:
and i need to retrieve the most recent outcome_date for testcase_id 1,
similarly i also need to retrieve the resulttype from the results
table(shown below) by using the join on outcomes.result_id ->
results.id, also for the most recent outcomes.outcome_date
+----+------------+
> id | resulttype |
+----+------------+
> 1 | Pass |
> 2 | Fail |
> 3 | N/A |
> 4 | Not Run |
+----+------------+
as you can see, a simple sql statement would be much more viable as an
option, but as you state the find_by_sql isnt so useful, i am
wondering
how such querying can be resolved in rails.
I would probably have an appropriate association defined and do
something like TestCase.find(1).outcomes.first (which will do what you
want as long as your outcomes association has the appropriate order
option)
or Outcome.find_by_test_case_id(1, :order => 'outcome_date desc')
I used it to get the most performance from my Rails app. This worked in
development environment. But surprisingly in production mode, the
find_by_sql was barely faster than a usual find().