Rails传递:datetime属性从模型到模型

时间:2017-10-30 22:11:22

标签: ruby-on-rails datetime

我尝试使主题具有:datetime属性,以便我能够在主题索引页面上显示最新讨论的主题。 :datetime由其帖子确定

关系如下

class Topic < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :topic
end

我试图制作@ topic.updated_at = @ post.updated_at 但它似乎不起作用。 所以我添加了一个新的属性disscuss_time:到主题模型,并使主题模型如下:

class Topic < ActiveRecord::Base
  has_many :posts

  before_save :default_values

  def default_values
    self.discuss_time ||= self.updated_at
  end
end

在我的post_controller中

class PostsController < ApplicationController
 def create  
    @topic = Topic.find(params[:topic_id])
    @topic.discuss_time = @post.updated_at
 end

Post.new位于主题控制器

并使视图像

     <% topics.order("discuss_time desc").each do |f| %>

这不行。虽然帖子显示在主题的显示页面上,但在我的管理页面中,diss_time为空。在主题的索引页面中,所有内容都是默认顺序。如何将:datetime属性表单模型传递给模型?

还有另一种方法,即在topic.post.count更改时更新主题。但这种方式似乎仍有一些问题。

1 个答案:

答案 0 :(得分:0)

class Topic < ActiveRecord::Base
  has_many :posts, after_add: :touch
end

这会在posts关联上创建一个回调,该关联调用touch(将created_at时间戳更新为当前时间)。

如果你确实需要的时间与创建的帖子完全相同,那么你可以这样做:

class Topic < ActiveRecord::Base
  has_many :posts, after_add: :update_ts!

  def update_ts(post)
    self.update_attribute(:created_at, post.created_at)
  end
end

您无需在控制器中执行任何特殊操作:

class PostsController < ApplicationController
   def create  
      @topic = Topic.find(params[:topic_id])
      @post = @topic.posts.new(topic_params)
      # ...
   end
end