Ruby on Rails:如何使用link_to将参数从视图传递到控制器,而不会在URL中显示参数

use*_*764 12 ruby-on-rails link-to

我目前在View中使用link_to帮助程序将title,author,image_url和isbn等参数传递给控制器

<%= link_to 'Sell this item',new_item_path(:title => title, :author => authors, :image_url=>image, :image_url_s=>image_s, :isbn=>isbn, :isbn13=>isbn13 ) %>
Run Code Online (Sandbox Code Playgroud)

然后,Controller将参数分配给稍后在View中的表单使用的对象(在new.html.erb中)

def new
      @item = Item.new

      @item.title = params[:title]
      @item.author = params[:author]
      @item.image_url = params[:image_url]
      @item.image_url_s = params[:image_url_s]
      @item.isbn = params[:isbn]
      @item.isbn13 = params[:isbn13]

      respond_to do |format|
        format.html # new.html.erb
        format.xml  { render :xml => @item }
      end
end
Run Code Online (Sandbox Code Playgroud)

然后将调用new.html.erb.这一切都运行正常,但网址显示所有参数

http://localhost:3000/items/new?author=Michael+Harvey&image_url=http://ecx.images-amazon.com/images/I/51vt1uVjvLL._SL160_.jpg&image_url_s=http://ecx.images-amazon.com/images/I/51vt1uVjvLL._SL75_.jpg&isbn13=9780307272508&isbn=0307272508&title=The+Third+Rail
Run Code Online (Sandbox Code Playgroud)

有什么办法可以让参数不显示在URL上吗?

Dan*_*nny 7

也许您可以编码参数并在控制器中解码它们以阻止可能想要修改URL的用户?可能有点矫枉过正但是......

>> author=ActiveSupport::Base64.encode64("author=jim")
=> "YXV0aG9yPWppbQ==\n"
>> ActiveSupport::Base64.decode64(author)
=> "author=jim"
Run Code Online (Sandbox Code Playgroud)


Joh*_*ley 2

我可以看到两个选项,都涉及 JavaScript:

  • 让链接填充参数的隐藏表单字段,然后使用 HTTP POST 请求提交表单
  • 让链接向控制器操作提交 AJAX 请求(使用 HTTP GET,除非单击链接会更改服务器端状态,在这种情况下应使用 POST)

我想我会采用第二种方法。