我的 Controller 中有一个显示操作:
# 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
我在同一个 Controller 中还有另一个 Action
def dosomething
@currentpost = ??
end
如何在 dosomething 操作中获取对当前显示帖子的引用?
最佳答案
你说 dosomething
是一个 Action 。这意味着,它是在单独的 HTTP 请求中调用的。
有几种方法可以在请求之间共享数据:
- 存储在 session 中
- 如果
dosomething
是表单的操作,则将其存储在表单的隐藏字段中 - 将其作为参数转发,如果
dosomething
被link_to
调用
- 如果
dosomething
是post
的一个 Action ,而所有这些都在PostsController
中,那么你有一个到达这个 Action 的路径:
在您的显示 View 中使用
<%= link_to 'do something', dosomething_post_path(@post) %>
在你的行动中
def dosomething
@currentpost = Post.find(params[:id])
....
end
在你的 routes.rb
你需要类似
resources :posts do
member do
get 'dosomething'
end
end
或用表格:
在你看来:
<%= form_for @message, :url => {:action => "dosomething"}, :method => "post" do |f| %>
<%= hidden_field_tag :post_id, @post.id %>
...
在您的 Controller 中:
def dosomething
@currentpost = Post.find(params[:post_id])
....
end
关于ruby-on-rails - 将变量从一个 Action 传递到另一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884117/