【问题标题】:Fetching only the first record in the table (via the view) without changing controller?仅获取表中的第一条记录(通过视图)而不更改控制器?
【发布时间】:2010-06-07 12:23:52
【问题描述】:

我试图只获取表中的第一条记录以进行显示。我正在创建一个用户可以上传多个图像并附加到帖子的网站,但我只想显示每个帖子的第一个图像视图。

进一步澄清posts belong_to projects。因此,当您在项目展示页面上时,您会看到多个帖子。在这个视图中,我只想显示每个帖子的第一张图片。有没有办法在视图中执行此操作而不影响控制器(稍后我希望允许用户通过添加灯箱浏览所有照片)。这是我的 /views/posts/_post.html.erb 代码:

<% div_for post do %>

    <% post.photos.each do | photo | %>

        <%= image_tag(photo.data.url(:large), :alt => '') %>
        <%= photo.description %>
    <% end unless post.photos.first.new_record? rescue nil %>

        <%= link_to h(post.link_title), post.link %>
        <%=  h(post.description) %>

        <%= link_to 'Manage this post', edit_post_path(post) %> 

<% end %>

更新: 我正在使用照片模型将多张照片附加到每个帖子并在此处使用回形针。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    其中任何一个都应该有效吗?

    post.photos.find(:first)
    
    or 
    
    post.photos.first
    

    编辑:我认为修改后的代码应该是这样的?

    <% div_for post do %>
        <% photo = post.photos.first %>
    
        <%= image_tag(photo.data.url(:large), :alt => '') %>
        <%= photo.description %>
    
        <%= link_to h(post.link_title), post.link %>
        <%=  h(post.description) %>
    
        <%= link_to 'Manage this post', edit_post_path(post) %> 
    <% end %>
    

    【讨论】:

    • 我是否必须保留“...do |photo|...”才能使其正常工作。我是 ruby​​ 和 rails 的新手,你能包含完整的语法吗?
    • 仅供参考,当我执行&lt;% post.photos.first do | photo | %&gt; 时,图像根本不会显示。请参阅我的编辑,照片位于照片表中,并通过照片模型附加以发布,没有照片(或视图)控制器。
    • first 将返回一个对象,其中照片返回一个数组,所以不,你不需要 do 块,将更新
    • 完美运行。非常感谢。
    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多