我有一个带有名为“published_at”的日期时间字段的帖子模型。在我的表单上,我有一个名为“publish_now”的属性的复选框(见下文)。当用户选中我的虚拟属性的复选框时,我希望将“published_at”设置为 Time.now():publish_now。
<input class="boolean optional" id="post_publish_now" name="post[publish_now]" type="checkbox" value="1" />
这是我在控制器中的创建和更新方法:
def create
@post = Post.new(params[:post])
if current_user
@post.author_id == current_user.id
end
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def update
@post = Post.find(params[:id])
respond_to do |format|
if @post.update_attributes(params[:post])
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
这是我的模型:
class Post < ActiveRecord::Base
belongs_to :author, class_name: "User", foreign_key: "author_id"
attr_accessible :author_id, :content, :published_at, :title, :publish_now
validates_presence_of :content, :title
def publish_now
!published_at.nil?
end
def publish_now=(value)
if value == "1" && published_at.nil?
published_at = Time.now()
end
end
end
这是我根据虚拟属性上的 railscast 应该如何工作的最佳猜测,但它并没有为 published_at 保存值。问题可能出在哪里的任何建议?
更新:(表单视图)
<%= simple_form_for(@post) do |f| %>
<%= f.input :title %>
<%= f.input :content, input_html: { cols: 100, rows: 10, class: "
span5" } %>
<% if @post.published_now == false %>
<%= f.input :publish_now, as: :boolean %>
<% end %>
<%= f.submit %>
<% end %>
更新示例日志:
Started POST "/posts" for 127.0.0.1 at 2012-10-31 14:14:49 -0500
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zlZ3s18VXwEvONIkk1CZAYESAEAxPP1OKcUtiyEuZgA=", "post"=>{"title"=>"big big love a doodle", "content"=>"aksdfj;skjf;kasjdf; lkj af;lk ;askdfj ;lk ;laf; ksd ;f", "publish_now"=>"1"}, "commit"=>"Create Post"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
(0.2ms) BEGIN
SQL (0.7ms) INSERT INTO "posts" ("author_id", "content", "created_at", "published_at", "title", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["author_id", nil], ["content", "aksdfj;skjf;kasjdf; lkj af;lk ;askdfj ;lk ;laf; ksd ;f"], ["created_at", Wed, 31 Oct 2012 14:14:49 CDT -05:00], ["published_at", nil], ["title", "big big love a doodle"], ["updated_at", Wed, 31 Oct 2012 14:14:49 CDT -05:00]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/posts/5
Completed 302 Found in 18ms (ActiveRecord: 2.1ms)