私の投稿モデルには、「公開済み」と呼ばれるブール値があります。
schema.rb: *
create_table "posts", :force => true do |t|
t.string "title"
t.string "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "published", :default => false
end
trueの場合、投稿は公開済みと見なされ、ユーザーのプロファイルの公開済みセクションに表示されます。falseの場合、ドラフトセクションに表示されます(申し訳ありませんが、コードの重複に対処する方法がわかりません)。
post_controller.rb:
class PostsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
def index
@posts = Post.all
end
等...
users_controller.rb:
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
@posts = @user.posts
end
等...
_shared / posts.thml:
<h2>Published</h2>
<% @posts.each do |post| %>
<% if post.published? %>
<div id="post-<%= post.id %>" class="post">
<%= image_tag post.image.url(:medium) %>
<h2 class="post-title"><%= link_to post.title, post %></h2>
<%= link_to post.user.email, post.user %>
<p><%= post.content %></p>
</div>
<% end %>
<% end %>
<h2>Draft</h2>
<% @posts.each do |post| %>
<% if not post.published? %>
<div id="post-<%= post.id %>" class="post">
<%= image_tag post.image.url(:medium) %>
<h2 class="post-title"><%= link_to post.title, post %></h2>
<%= link_to post.user.email, post.user %>
<p><%= post.content %></p>
</div>
<% end %>
<% end %>
例:
users.html.erb:
<h2>User Show</h2>
<%= image_tag @user.avatar.url(:medium) %>
<span>Email: <%= @user.email %></span><br />
<span>ID: <%= @user.id %></span><br />
<%= render 'shared/posts' %>
index.html.erb
<%= render 'shared/posts' %>
(ビューが少し乱雑であることはわかっています。後で、各投稿ドラフトの横に「ドラフト」というテキストを表示するだけだと思います)。
問題は、投稿がcreated_at
日付でソートされることです。投稿のインデックスページの日付で並べ替えてほしいpublished_at
(もっと理にかなっていると思う)。
published_at
t.datetime
移行によってフィールドを追加する方法を知っています。published_at
しかし、フィールドのロジックにどのコードを使用するかはわかりません。
助言がありますか?
(ちなみに、何がより正確に聞こえますか?' published_at
'または' published_on
'?)