我的 Post 模型有一个名为“published”的 bool 值:
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,则出现在草稿部分中(抱歉,但我不知道如何处理代码重复)。
posts_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' %>
(我知道这些 View 有点困惑。我想稍后我会在每个帖子草稿旁边显示一条文字,写着“草稿”)。
问题是帖子将按其created_at
日期排序。我希望它们按帖子索引页中的 published_at
日期排序(我认为这更有意义)。
我知道如何通过迁移添加 published_at
t.datetime
字段。但我不确定 published_at
字段中的逻辑使用什么代码。
有什么建议吗?
(顺便问一下,哪个听起来更正确?“published_at
”还是“published_on
”?)
最佳答案
在您的表中添加published_at
(日期时间)字段。当您发布时更新published_at字段,然后当您获取数据时使用 order('published_at Desc')
@posts = @users.posts.order('published_at DESC')
与 Controller 中的逻辑相同
if params[:post][:published] == true # whatever you got in controller rather than params[:post][:published]
@post.published_at = Time.now
else
@post.published_at = ""
end
这意味着,当 published
值为 true 则上面的代码在您的 Controller 中执行,并在您的published_at 字段中添加值 Time.now,如果published 的值为 false,则上面的代码不会执行,所以 published_at
字段有空白值。
或者,通过使用类似的模型
before_save :published_post
def published_post
if self.published == true
self.published_at = Time.now
end
end
关于ruby-on-rails - 将 'published_at' 字段添加到具有 'published' bool 字段的 Post 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12985265/