I have a controller action where I'd like to receive form data, execute some business logic, then refresh the form. This works Ok if I save the object in the database then use a redirect_to. I would prefer the controller edit the object in memory and render the response directly.
For example, take a standard rails 5.1.4 generated app generated like so:
rails new turbolinks_example
rails g scaffold Thing name
rails db:migrate
The form, slightly edited for brevity and to enable turbolinks:
<%= form_with(model: thing) do |form| %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name, id: :thing_name %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
A) Now we edit the controller to change the object. This uses a redirect to edit and works:
ThingsController < ApplicationController
...
def update
if #thing.update(thing_params)
#thing.update name: "#{#thing.name} is OK"
redirect_to edit_thing_path(#thing)
end
end
B) This uses a render and does not work:
class ThingsController < ApplicationController
...
def update
if #thing.update(thing_params)
#thing.name = "#{#thing.name} is OK"
render :edit
end
end
end
With A)
- Update request is received by controller
- Object is modified (& saved)
- Redirect is returned
- Rediredted url is rendered
- DOM is updated
With B)
- Update request is received by controller
- Object is modified (in memory)
- Response is rendered
- Response is received by browser, but ignored
The response received, looks correct. Full HTML, with the changes made to the object. How do I get turbolinks to notice it and replace document.body like normal?
The full project, including development.log is on Github
The problem is that, in Rails 5:
Forms are remote by default: they are sent via AJAX unless local: true provided
When rendering HTML as a response to an AJAX call, nothing happens unless, of course, there is custom javascript in the client handling the response
Turbolinks is enabled by default, which handles redirect_to properly, but does nothing for render
I think this is an inconsistency in Rails that causes much confusion, such as the problem you exposed with your code. I created a gem turbolinks_render to deal with this problem. I also wrote a little post on this very same problem.
I hope that, one way or other, this gets fixed in future Rails versions.
Related
Rails 3.2.1: I have the following div that calls a partial
<div id="weighin">
<%= render :partial => "my_weight/weighin" %>
</div>
The partial contains a form that posts ajax (ie has :remote => true) to a controller with:
respond_to do |format|
format.js
end
The .js.erb file has a single line:
$("#weighin").html("<%= render :partial => "my_weight/weighin1" %>");
The _weighin1.html.erb partial file has a single line:
<p><%= #my_weight[1].weight %></p>
This works, in that the original div is replaced with the value of the #my_weight field - so the fundamental structure is all working ok
However, Rails will not handle any more code in the partial - if I add so much as a carriage return to the end of that one line, the server log confirms all ok, but no script gets run on the page - ie nothing changes.
The same happens if I try to put more html in the partial, but put it all in a single line - this doesnt run either.
How can I output more than a single short statement in a partial?
OK, I figured this out:
$("#weighin").html("<%= escape_javascript(render :partial => "my_weight/weighin1") %>");
escape_javascript is essential
What is confusing is that, depending on what is in the html() you are sending, this will sometimes work without escape_javascript, leading one to a false conclusion... :-)
I'm trying to implement an 'edit' link that brings up a form to change a displayed attribute on a page.
My layout has:
<div id="company_info">
<%= yield :company_info %>
</div>
<div id="edit_company_info">
</div>
My view has:
<%= content_for :company_info do %>
<%= render 'company_info' %>
<%= link_to "Edit", 'company_info_form', :class => 'btn btn-mini', :method => :get, :remote => true %>
My controller has:
def company_info_form
#company = Company.get(params[:id])
respond_to do |format|
format.js
end
end
My company_info_form.js.erb file has:
$('#edit_company_info').html("<%= escape_javascript(render "company_info_form") %>");
Upon clicking the link, my server shows:
Started GET "/companies/company_info_form" for 127.0.0.1 at 2012-03-12 20:19:13 -0700
Processing by CompaniesController#show as JS
Parameters: {"id"=>"company_info_form"}
Completed 500 Internal Server Error in 1ms
RuntimeError (Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id):
app/controllers/companies_controller.rb:9:in `show'
So I think this is a routing issue-- but I have no idea how to fix it. How do I get the company_id param that is on my current page to be recognized by the partial I'm loading as well?
I'm on /companies/1, but the link is to companies/company_info_form, losing the "company_id = 1" param.
Yes, the issue is with your routes and with your link as you have pointed out.
The first issue can be ascertained as it says Processing by CompaniesController#show as JS. So, its actually going to companies#show where it tries to find a company based on id. But, since no correct id is passed, it errors out.
The second issue is because your link is to companies/company_info_form, as you pointed out, since you have used 'company_info_form' as the path in your link for edit. And you haven't passed current company to the link either.
Since you haven't posted your routes file, which you should have, since you have identified a potential problem with routes , I'll present my own.
In your routes :
resources :companies do
member do
get 'company_info_form'
end
end
That will provide you with
company_info_form_company GET /companies/:id/company_info_form(.:format) companies#company_info_form
Then you can provide the link as :
<%= link_to "Edit", company_info_form_company_path(#company) %>
I am currently following the Ruby on Rails Tutorial by Michael Hartl. And there is something that has been bugging me for quite some time. I looked it up but I still can't find a good answer.
Anyway, I've noticed is when you have a validation error in the signup page it renders the original signup page and changes the nav bar address. I've matched /signup to the action new, but if I use render it changes from /signup to /users (the default, because of the RESTful standard I guess).
I'll leave some lines of my code:
routes.rb
resources :users
match '/signup', :to => 'users#new'
users_controller.rb
def new
#user = User.new
#title = "Sign up"
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to user_path(#user)
else
#title = "Sign up"
#user.password = ""
#user.password_confirmation = ""
render 'new'
end
end
So I've tried to work around this by not using the render method but redirect_to instead but I'm having trouble using it. As it is actually sending data to the path provided, #user.errors gets overwritten by creating a new instance of the model and the flash variable cannot show the errors.
_errors.html.erb
<% if #user.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(#user.errors.count, "error") %>
prohibited the user from being saved:
</h2>
<p>There were problems with the following fields:</p>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
My question is: is there any way that by using render I can change the url displayed on the navbar? It's really frustrating if someone makes a mistake in the signup form, presses enter in the navbar and ends up in a totally different place.
The reason why the address changes is because you have performed a POST request to /users/ therefore the browser is doing the correct thing by displaying the different address.
There are a few of ways around this:
Store the invalid User object and redirect back to the Users.new action.
Change the URL of the Users.create action.
Use history.replaceState to change the user's address bar.
The first option keeps the controller more RESTful, however it will need use of the :session or flash to persist the data across the redirect.
The second option keeps the code simpler, but involves fiddling with the routes.rb file.
The third option relies on javascript and support for HTML5 to mess with the user's browser history.
Personally I would leave the URL as is, but if I had a client who insisted on doing this, I would go for the second option.
I have worked out how to disable the authenticity_token in the controller but rails still creates the field in the forms. How do i turn this off as the server i am posting the form to needs a very specific set of field names.
In rails after 3.2.x you can pass a parameter into the form generator as suggested in another answer:
form_for #invoice, :url => external_url, :authenticity_token => false do |f|
...
<% end %>
In any rails version you can disable globally in config/application.rb, as in another answer:
config.action_controller.allow_forgery_protection = false
In rails 3.0.x you can disable on a page load basis in the controller by overriding the following method. Unfortunately, there seems to be no way to do this at the form level.
protected
def protect_against_forgery?
if ...
# results in the meta tag being ommitted and no forms having authenticity token
return false
else
# default implementation based on global config
return allow_forgery_protection
end
end
To disable it across your application, you can add this line to your config/application.rb:
config.action_controller.allow_forgery_protection = false
For external urls you can turn this of per form as follows:
<%= form_for #invoice, :url => external_url, :authenticity_token => false do |f|
...
<% end %>
Source: http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for
I'm upgrading from Rails 2.3.8 to 3.0.3 and notice that my code for nested layouts isn't working.
In my main Application layout I have the line
<%= controller.sub_layout %>
which then looks to the controller, who has:
def sub_layout
render :inline => "<%= yield %>"
# or otherwise some partial for the sub-layout
end
The problem is, this doesn't get rendered! If I put a direct <%= yield %> statement in the layout, it does work. So the question is, what's happening here, and how do I fix it?
This worked beautifully in Rails 2.3.8
How about a much saner approach:
render :layout => false
Related: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
So you all have some more of a background on this, the whole sub-layout approach was based on this blog post: Sorta Nested Layouts (The solution is given in the comments section.)
Instead of making a controller method sub_layout, any controller that uses a sublayout needs to define a before_filter method that sets a variable:
def inner_layout
#inner_layout = 'layouts/sublayout_partial_name'
end
then in the main layout.html.erb (i.e. application.html.erb), where you would otherwise put your yield statement:
<%= #inner_layout ? render(:partial => "#{#inner_layout}") : yield %>
the assumtion is that the sublayout partial file will have its own yield statement in there somewhere.