开发者

Rails 3 - how to work with data got from database

I am loading from database the only row. The data are stored in variable (e.g.) @data. In view, if I want to display the value got from database, I have to do following:

    <% @data.each do |d| %>
        <%=d.name %>
    <%end%>

And I would like to ask you - exist any better way? I think it's a bit silly for the only row to use loop... I tried something like

<%= @data.name %>
OR
<%= @data.each.name %>

But in both cases I got the error message about bad syntax...

So to my question - is possible to get display data a bit more elegantly?

EDIT: my query: @data = Car.inc开发者_JAVA技巧ludes(:tyres).where("param1 = ?", params[:param1])


If you've loaded more than one model (row), then a loop is the natural construct for displaying each value. If you're really set on a one-liner, you could use some of Ruby's list comprehensions:

<%= @data.map(&:name).join(" ") -%>


I think that you are loading .all instead of .first.

In your controller,

@data = Data.where(:some => 'condition').first

or

@data = Data.find(params[:id])
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜