将变量从一个动作传递到另一个动作

Ayr*_*rad 3 ruby-on-rails ruby-on-rails-3.1

我在我的控制器中有一个show动作:

  # GET /posts/1
  # GET /postings/1.json
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @posts }
    end
  end
Run Code Online (Sandbox Code Playgroud)

我在同一个控制器中也有另一个动作

  def dosomething
      @currentpost = ??
  end
Run Code Online (Sandbox Code Playgroud)

如何在dosomething操作中获得对当前显示的帖子的引用?

Mar*_*n M 8

你说dosomething是一个动作.这意味着,它在单独的HTTP请求中调用.

有几种方法可以在请求之间共享数据:

  • 存储在会话中
  • 将其存储在表单的隐藏字段中,如果dosomething是表单的操作
  • 将其作为参数转发,如果dosomething由a调用link_to
  • 如果dosomething是a的操作,post并且所有这些都在,PostsController并且您有一个指向此操作的路径:

在你的节目视图中使用

<%= link_to 'do something', dosomething_post_path(@post) %>
Run Code Online (Sandbox Code Playgroud)

在你的行动中

def dosomething
  @currentpost = Post.find(params[:id])
  ....
end
Run Code Online (Sandbox Code Playgroud)

routes.rb你需要的东西像

resources :posts do
  member do
    get 'dosomething'
  end
end
Run Code Online (Sandbox Code Playgroud)

或者使用表格:
在您看来:

<%= form_for @message, :url => {:action => "dosomething"}, :method => "post" do |f| %>
   <%= hidden_field_tag :post_id, @post.id %>
...
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

def dosomething
  @currentpost = Post.find(params[:post_id])
  ....
end
Run Code Online (Sandbox Code Playgroud)