How to redirect using custom format routes in Rails? - ruby

I'm working on a simple app that requires me to redirect to a show action after the update action.
I have this route for show.
match '/user/:fullname' => 'items#show'
Which gives me this controller.
#user = User.find_by_fullname(params[:fullname])
However, after the update method of user,
def update
if #user.update_attributes(params[:user])
format.html { redirect_to #user } # Don't need to pass parameters here.
else
format.html { render action: 'edit' }
end
end
It redirects me to the original format of show action which is:
sampleapp.dev/users/1
How can I redirect to show action using the format I specified in the routes.rb which is by fullname?
sampleapp.dev/users/johndoe

Change this line to:
match '/user/:fullname' => 'items#show', :as => :custom_show_item
then change your redirect to:
redirect_to custom_show_item_path(:fullname => #user.fullname)

Related

Ruby render partial on form submit on same page

I am trying to render a partial that I made on top of the current page after a form submit. This should happen in the controller's create method, but I can't seem to figure out if this can be done in Ruby, or if I should just render it using Javascript.
Here is what I have tried so far:
Created a partial in the same folder as the new.html.erb (called _lightbox.html.erb)
The controller render changed to this:
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
BackgroundJob.perform_async(#user.id)
format.html { render :partial=>"lightbox", :layout=>false}
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
I have read up on render, however using the :partial key it simply renders the partial on a new page. I should probably just change the form to use :remote and add the lightbox-esque content with an ajax success, however I was curious as to if this can be done with Ruby on Rails with its rendering functionality.
The code you've displayed here isn't really the problem. It's all in the view.
You need to prevent the default action from form submission, which is to post to the form URL. If the browser posts to that URL, it will render the response. Once you've prevented the default action, you'll then need to submit the form yourself using javascript and set up a callback to deal with the response. That callback should put the html in the place you want it in the page. If any parts of this are unclear, I can expand upon them.

Rendering ajax result in different view Rails 3

Given that I have the routes.
root :to => 'pessoas#index'
post '/pessoas' => 'pessoas#create'
And my view app/view/pessoas/index.haml has the following view code. (Submit here will post to pessoas#create)
= form_tag "/pessoas", :method => :post, :remote => true, :id => "participe" do
...
= button_tag "Sign up", :class => "envia"
And my create.js.erb view is.
$('#user-feedback').html('<%= #message %>');
And the controller code simply saves the model.
def create
#pessoa = Pessoa.new(params[:cliente])
if #pessoa.save
#message = "Success"
else
#message = "Failure"
end
respond_to do |format|
format.js
end
end
Then I go to the root path /
And I fill the form and click on submit.
Then the element p#user-feedback haven't been changed. Why?
I notice in app's log: that the request was done right and the jquery also but it render at /pessoas response but not at current view (index).
What can I do? Or should I just forget about this and make this with $.ajax way?
I want a way to provide feedback to the users.

rails insert ajax via jquery

Good day!
I'm trying to implement ajax in my rails test app.
my controller code app/controllers/admin/data
class Admin::DataController < ApplicationController
...
def ajax
if params[:ajax] == 'list'
#responce = Admin::Datum.all
else
#responce ={error: true}
end
respond_to do |format|
# format.html { redirect_to #user }
# format.js
format.json { render json: #responce }
end
end
end
index.js.erb
alert('1');
$.post('/admin/data/ajax',{ajax:'list'},function(responce){
alert('2');
console.log(responce);
}
);
could you help me in determining the url that i've to use in ajax to access ajax method?
or any other help is very welcome!
Update 1
Updated initial code to represent more complex problem
I added to routes.rb
match 'admin/data/ajax' => 'Admin::Data#ajax'
could be any url, it's what you write in your jquery.
And it works!

Updating (Hiding) a group of objects in Rails 3

I've some difficulty in determining any way to update my objects as a group. I have an Alert model which has some alerts for the user. I'd like to provide a way to update them in bulk, as I've noticed that I often want to. I just don't know Rails well enough to know what 'the Rails way' would be.
My controller:
class AlertsController < ApplicationController
def index
#alerts = Alert.all(show: true)
end
def destroy
alert = Alert.get(params[:id])
## I lied, I'm not really deleting things, just hiding them from showing
alert.update(show: false) if alert
respond_to do |format|
format.js { render :nothing => true }
end
end
I've been using this code in my *.html.haml view to create the delete link for each individual alert:
- #alerts.each do |alert|
%span{ :class => 'description' }=alert.description
= link_to "Destroy", alert, :confirm => "Are you sure", :method => :delete, :remote => :true
What I want to have is a link on my index page Delete All which I could use to hide(update) all of the alerts. I've been attempting this with a destroy_all method for my controller, but I felt like it wasn't quite the right approach, as I didn't know how to link to something like that. Thank you for pointing me in the right direction.
Here is the destroy_all method I'd hacked together, for reference.
def destroy_all
#alerts.each do |alert|
alert.update(show: false) if alert
respond_to do |format|
format.js {render :nothing => true}
end
end
end
I don't know how you have routed to this controller but I would probably do something like this:
#routes.rb
resources :alerts do
delete :remove_all, :on => :collection
end
This will create a route looking like /alerts/remove_all which can only be called through the DELETE protocol. By specifying :collection it tells the routing the this route is not a sub route to one specific Alert so no :id is included.
Then the controller action could probably look something like this:
def remove_all
Alert.update_all({ show: false }, { show: true })
respond_to do |format|
format.js {render :nothing => true}
end
end
The update_all function will make sure that there is only one database update instead of one for each alert that is to be removed. The first argument is a hash containing the updates and the second argument is a hash with the conditions for which records are to be updated.
And from the view you should be able to link to the action like this:
= link_to "Remove All", remove_all_alerts_path, :confirm => "Are you sure", :method => :delete, :remote => :true
remove_all_alerts_path is a path helper that is automatically generated when you use the above syntax in routes.rb

Form behavior posting nested resource

I am using Ruby on Rails 3 and I would like to change its conventional behavior on posting a form in order to post from a signup action to the create action instead that from the new action. That is, I would like to use the signup action instead of the (conventional) new action in my User controller and trigger the create action to save my model data that contains nested resources.
In my /config/routes.rb file I have:
resources :users do
collection do
get 'signup'
end
resource :profile
end
In my /app/controllers/users_controller.rb I have
class UsersController < ApplicationController
def signup
#signup_user = User.new(params[:user])
#signup_user.build_profile # NOTE: Nested resource
...
end
def create
...
#signup_user.save
respond_to do |format|
format.html { render :action => :signup } # signup.html.erb
end
end
end
In my /app/views/users/signup.html.erb file I have
<%= form_for #signup_user do |f| %>
...
<% end %>
My problem is that if I submit the above form, I will be redirected to the index action of the user controller and not to the create action I expect. It seams that the form posts only to the index action.
How can I solve the problem?
I tryed to use the following
<%= form_for( :user, #signup_user, :url => { :controller => "users", :action => "create" }, :html => { :method => :post } do |f| %>
but I have still the problem: I am redirected to the index action.
SOLUTION
The problem did seam to be in the routers.rb. The correct code was
resources :users do
collection do
get 'signup'
post 'create'
end
resource :profile
end

Resources