用于为Post设置published_at的虚拟属性

时间:2012-10-31 19:26:18

标签: ruby-on-rails

我有一个名为“published_at”的日期时间字段的帖子模型。在我的表单上,我有一个名为“publish_now”的属性的复选框(见下文)。当用户选中我的虚拟属性的复选框时,我希望将“published_at”设置为Time.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)

1 个答案:

答案 0 :(得分:3)

错误在此行

published_at = Time.now()

应该是

self.published_at = Time.now()

括号也是可选的。 如果你赋予某些东西,那么Ruby会认为它是一个局部变量,除非你明确地提供了这个对象,只有这样Ruby才能知道它实际上是你想要调用的方法(published_at = method)。这是Ruby中常见的问题。

您的代码中发生的是创建一个新的本地变量published_at。有关详细信息,请参阅“使用类中的访问者”中的http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html

当读取类似的属性时,你不需要为self加前缀,但是因为Ruby在你分配它之前不会假设某个东西是局部变量。所以在published_at = ...之前,Ruby会将published_at视为一个方法调用,在你执行published_at = ...(没有前面的self)之后,它会将published_at视为一个局部变量。只有这样你才必须使用self.published_at来实际调用方法而不是读取局部变量。对于属性writter(以=结尾),您始终需要为对象添加前缀。您也可以使用属性hash,这样您就不需要为self加前缀:

attributes["published_at"] = whatever