如何在Rails中为不同的模型定义前一个?

时间:2016-04-26 17:37:17

标签: ruby-on-rails modal-dialog

Rails默认为<button onclick="showExternalHelp()">Show Help</button> <script type="text/javascript">function showExternalHelp() { var location = window.location.pathname; var splitter = "\\"; var lastIndex = location.lastIndexOf(splitter); location = location.substring(0, lastIndex); location = location + "\\External.chm"; window.showHelp(location); }</script> 。在ruby中是否有.next方法,我应该自己定义吗?

.previous

我在我的照片模型中定义它,它适用于我的照片视图,但这在用户视图中使用。是否需要在用户模型中定义?

users_controller.rb

"#{photo.id.previous}"

show.html.erb(用户)

def show
    @user = User.find(params[:id])
    @photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end

user.rb

<% @photos.in_groups_of(3, false).each do |group| %>
    <div class="row">
      <% group.each do |photo| %>
        <a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>
          <div class="col-xs-4 insta">
            <%= image_tag(photo.picture.ad.url, class: "img-responsive") %>
          </div>
        </a>  
        <div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">x</span>
          </button>
...
...
...

<a class="prev" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.previous}"%>>
  "Previous"
</a>
<a class="next" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.next}"%>>
   "Next"
</a>

3 个答案:

答案 0 :(得分:2)

你可以找到这样的记录:

class User
  def self.previous_by_id(id)
    where("id < ?", id).last
  end
end

User.previous_by_id(5)
#=> #<User:0x0000000741b818 id: 4 .....>

或者如果你想像实例方法那样定义它:

class User
  def previous
    self.class.where("id < ?", id).last
  end
end

答案 1 :(得分:1)

Ruby已经有了这个方法。例如:

1.pred
# => 0

查看this了解更多详情

Rails也支持这一点。例如:

photo.id.pred

答案 2 :(得分:0)

class User
  def previous
    self.class.where("id < ?", id).last
  end
end

class User
  def next
    self.class.where("id > ?", id).first
  end
end

href=<%="#"+"#{photo.previous.id}"%>>

href=<%="#"+"#{photo.previous.id}"%>>