查询活动记录和外键帮助[Rails 4]

时间:2013-11-24 19:49:57

标签: ruby-on-rails-4 rails-activerecord

我知道有很多不同的方法可以做到这一点,但使用http://guides.rubyonrails.org/active_record_querying.html,我一直无法找到适合我的最佳方式。

我正在使用RoR制作论坛,我在删除主题中的帖子时遇到了问题。

每个主题都有很多帖子。每篇文章都有一个主题。

当您在主题中发帖时,它会更新主题表,其中包含上次发布的人和时间。但是,当您删除帖子时,它会保留帖子的旧数据。

当我删除帖子时,我需要使用之前帖子的数据更新主题表。

我知道删除后,我需要查询主题中的所有帖子,找到最后一个帖子并使用其数据来更新主题。

虽然我怎么做?

查询将类似于

SELECT * FROM posts WHERE(topic_id = topic.id)ORDER BY id DESC

后置控制器

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = Post.new
  end

  def edit
    @post = Post.find(params[:id])
  end

def create  
  @post = Post.new(
    :content => params[:post][:content], 
    :topic_id => params[:post][:topic_id], 
    :user_id => current_user.id)  

  if @post.save  
    @topic = Topic.find(@post.topic_id)  
    @topic.update_attributes(
      :last_poster_id => current_user.id, 
      :last_post_at => Time.now)  
    flash[:notice] = "Successfully created post."  
    redirect_to "/topics/#{@post.topic_id}"  
  else  
    render :action => 'new'  
  end  
end  

def update  
  @post = Post.find(params[:id])  
    if @post.update_attributes(params[:post].permit!) 
    @topic = Topic.find(@post.topic_id)  
    @topic.update_attributes(:last_poster_id => current_user.id, :last_post_at => Time.now)  
    flash[:notice] = "Successfully updated post."  
    redirect_to @post  
  else  
    render :action => 'edit'  
  end  
end  

  def destroy
    @post = Post.find(params[:id]) 

    @post.destroy

    **# WHAT QUERY STATEMENT GOES HERE** 

    @topic.update_attributes(
      :last_poster_id => @post.user_id, 
      :last_post_at => @post.created_at)  
      redirect_to "/topics/#{@post.topic_id}"

  end
end

1 个答案:

答案 0 :(得分:1)

尝试使用此代码:

def destroy
  @post = Post.find(params[:id])
  @topic = @post.topic
  @post.destroy
  last_post = @topic.reload.posts.last
  @topic.update_attributes(last_poster_id: last_post.user_id, last_post_at: last_post.created_at)
  redirect_to @topic
end
相关问题