誰だので、ここに私のことを示唆している:
class User
# Runs the supplied block with user's last post. If user
# doesn't have a last post, then the block won't run.
def with_last_post
raise ArgumentError unless block_given?
posts.last && yield posts.last
end
# Runs the supplied block only if the user has posts
def having_posts
raise ArgumentError unless block_given?
yield if posts.any?
end
# Runs the supplied block if the user has no posts
def without_posts
raise ArgumentError unless block_given?
yield if posts.any?
end
end
<% current_user.with_last_post do |last_post| %>
<%= "last post in past!" if last_post.date.past? %>
<% end %>
<% current_user.having_posts do %>
<%= "last post in past" if current_user.posts.last.date.past? %>
<% end %>
<% current_user.without_posts do %>
You haven't posted anything!
<% end %>
それを行う意図正しい方法のような何かを行うことによって、コントローラ内のビューで必要な情報を収集するために、次のようになります。
# FooController:
def show
@last_post = current_user.posts.last
end
# views/foo/show.html.erb :
<%= render 'last_post', last_post: @last_post %>
# views/foo/_last_post.html.erb :
<% if @last_post %>
Last post: <%= @last_post.date %>
<% else %>
You haven't posted anything ever.
<% end %>
またはヘルパーを使用して:
# app/helpers/foo_helper.rb
module FooHelper
def user_last_post_date
last_post = current_user.posts.last
if last_post
last_post.date.past? "in the past" : "in the future(??!)"
else
"never"
end
end
end
# app/views/foo/show.html.erb
Last post date: <%= user_last_post_date %>
ください。あなたの問題を解決したものを受け入れたものとして確認してください。これはSOの推奨動作です。 –