如何重定向到数组中的对象

时间:2016-12-07 04:30:23

标签: ruby-on-rails ruby

我有行动index

def index
  if params['type'] == 'random'
    @objects = Object.order("RANDOM()").limit(1)
  else
    @objects = Object.all.limit(1)
  end
end

create操作:

def create
  object = Object.find(params[:object_id])
  comment = object.comments.create(params[:comment].permit(:body))

  respond_to do |format|
    format.html 
    format.js #ajax
  end

  if comment.save
    redirect_to root_path(params[:object_id]) #doesn't work
  else
    flash[:error] = comment.errors.full_messages[0]
    redirect_to root_path(params[:object_id]) #doesn't work
  end
end

我可以在index页面中评论一个对象。当我发表评论时,我想重定向到评论的对象。

使用我的代码,重新加载页面,但显示下一个对象,我看不到评论。如何重定向到同一个对象?

我的root_path

<span class="random-icon"><%= link_to icon('random'), "http://localhost:3000/?type=random" %></span>

<div class="inner-container">
    <% @objects.each do |object| %>
      <h1 class="title"><%= object.title %></h1>
      <p class="obj"><%= object.body %></p>
      <h3 class="comments-title">Comments:</h3>
      <div id="comments">  
        <% object.comments.each do |comment| %>
          <div class="comments"> <%= comment.body %> 
            <span class="time-to-now"><%= distance_of_time_in_words_to_now(comment.created_at) %> ago</span>
          </div>
        <% end %>
      </div>

        <div id="error"><%= flash[:error] %></div>
        <%= form_for([object, object.comments.build], remote: true) do |f| %>
          <%= f.text_area :body, class: "text-area" %> 
          <p class="char-limit">255 characters limit</p>
          <%= f.submit "Comment", class: 'button' %>
        <% end %>
    <% end %>
</div>

2 个答案:

答案 0 :(得分:1)

如果params['type']为真,则Object.order("RANDOM()").limit(1)将始终被重新评估,并且通常会返回一个新对象。为了确保您返回到同一个对象,您可能希望将其存储在会话中,然后在您的会话中首先检查您的会话中是否有喜欢的评论,如果是,@objects = Object.find(session[:comment_object_id])

def index
  if session[:comment_object_id]
    @objects = Object.find(session[:comment_object_id])
    session.delete(:comment_object_id) # delete the session after use
  elsif params['type'] == 'random'
    @objects = Object.order("RANDOM()").limit(1)
  else
    @objects = Object.all.limit(1)
  end
end


def create
   object = Object.find(params[:id])
   comment = object.comments.create(params[:comment].permit(:body))

  respond_to do |format|
    format.html 
    format.js #ajax
  end

  if comment.save
    session[:comment_object_id] = :object_id # set the session here
    redirect_to root_path # should work now
  else
    flash[:error] = comment.errors.full_messages[0]
    redirect_to root_path #should work now
  end
end

答案 1 :(得分:0)

这很简单,而且非常接近。

create方法中,您已获得要重定向到的object。所以只需在if comment.save中直接使用它:

redirect_to object_path(object)

您可以通过以下命令获取所有这些path“助手”的列表:

rake routes

顺便说一下,在那个列表中,你应该看到root_path不接受任何论据......以供将来参考。