rails 4重定向到最近创建的记录?

时间:2016-02-02 23:47:48

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

构建一个简单的消息传递应用using this tutorial,并想知道我是否可以重定向到数据库中最新的更新记录?

application.html.haml

= link_to 'Messages', :conversations

我希望能够将其更改为localhost:3000/messages,然后它会自动重定向到最近录制的消息。

的routes.rb

resources :conversations do
  resources :messages
end

conversation.rb

class Conversation < ActiveRecord::Base
  belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
  belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'

  has_many :messages, dependent: :destroy

  validates_uniqueness_of :sender_id, :scope => :recipient_id

  scope :between, -> (sender_id,recipient_id) do
    where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)
  end

end

messange.rb

class Message < ActiveRecord::Base
  belongs_to :conversation
  belongs_to :user
  validates_presence_of :body, :conversation_id, :user_id

  def message_time
    created_at.strftime("%m/%d/%y at %l:%M %p")
  end
end

messages_controller.rb

def index
  @conversations = Conversation.all
  @messages = @conversation.messages
  if @messages.length > 10
    @over_ten = true
    @messages = @messages[-10..-1]
  end
  if params[:m]
    @over_ten = false
    @messages = @conversation.messages
  end
  if @messages.last
    if @messages.last.user_id != current_user.id
      @messages.last.read = true;
    end
  end

  @message = @conversation.messages.new
end

不确定需要哪些信息,但只是想知道这是否可行。

1 个答案:

答案 0 :(得分:0)

我会做以下事情:

的routes.rb

get 'messages', to: 'messages#most_recent'

message.rb

class Message < ActiveRecord::Base
  belongs_to :conversation
  belongs_to :user
  #Create a scope for get the most recent record
  scope :most_recent, :order => "created_at DESC", :limit => 1
  validates_presence_of :body, :conversation_id, :user_id

  def message_time
    created_at.strftime("%m/%d/%y at %l:%M %p")
  end
end

messages_controller.rb

def most_recent
  @message = Message.most_recent.first
end

然后,您可以使用@messagemessages/most_recent.html.erb视图中显示最新消息。

但是,如果您仍希望保持index控制器操作正常,则需要添加条件。

您需要为most_recent控制器操作

添加单独的路由

的routes.rb

get 'messages/most_recent' #In this case is not necessary to specify controller action with to:

然后在index控制器操作

messages_controller.rb

def index
  if SOME CONDITION HERE
    redirect_to messages_most_recent_path
  else
    @conversations = Conversation.all
    @messages = @conversation.messages
    if @messages.length > 10
      @over_ten = true
      @messages = @messages[-10..-1]
    end
    if params[:m]
      @over_ten = false
      @messages = @conversation.messages
    end
    if @messages.last
      if @messages.last.user_id != current_user.id
        @messages.last.read = true;
      end
    end

    @message = @conversation.messages.new
  end
end

def most_recent
  @message = Message.most_recent.first
end