#my_page.html.erb
<%= form_tag save_text_path do %>
<%= text_field_tag :test_input, @text %>
<%= submit_tag "Update" %>
<% end %>
# in your controller
def my_page
@text= File.open('your_file.txt').read
end
def save_text
updated_text = params[:test_input]
# do something with the text
end
# in your routes.rb
post "save_text" => "your_controller_name#save_text", as: "save_text
我有这个代码,每当我点击提交时,它都会变为localhost:3000 / save_text的视图。如何在不更改视图的情况下更新文本
答案 0 :(得分:0)
您可以执行以下任一操作:
def save_text
updated_text = params[:test_input]
# do something with the text
# you have to pass in the @text instance var below. Pass in the text you want to
# display to that instance var
@text= updated_text
flash[:notice] = "Text saved"
render :my_page
end
#OR
def save_text
text = Text.create(params[:text_input]) #assumes params[:text_input] is a hash of text attributes
redirect_to my_page_path(text_id: text.id), notice: "Text saved"
end
def my_page
@text = Text.find(params[:text_id])
end
这两个选项都会导致页面刷新,但会显示相同的页面。重定向方法将引导您返回my_page网址,而呈现方法将呈现my_page模板,但将具有save_text网址。您也可以使用AJAX路由,但它会涉及更多。
答案 1 :(得分:0)
您可以将remote: true
与rails UJS模块(默认内置)一起使用,就像这样
<%= form_tag save_text_path, remote: true do %>
...stuff
<% end %>
这会通过AJAX将您的表单提交给服务器,然后在服务器上通常会生成一段javascript来操作您的页面,例如更新内容,显示闪烁等。
def save_text
...
render js: "alert('Hello');"
end