Rails Routing Redirects to wrong path - ruby-on-rails-3

I have a view called, "clients" which shows a list of calls from the Call database. That works fine. However when I added a new button with a form behind it the call will be created but it redirects to calls_path instead of clients_path.
I have no idea why it's doing this, my only theory is that I'm working with actions that touch data outside of the clients_controller and somehow Rails is defaulting to the calls_path. The same thing happens on my delete action. Can someone help me make sense of this?
calls_controller
def new
#call = Call.new :call_status => "open"
respond_with #call
end
def create
#call = Call.new(params[:call])
if #call.save
redirect_to clients_path, notice: "Call was successfully created."
else
render :new
end
end
def destroy
#call = Call.find(params[:id])
#call.destroy
respond_to do |format|
format.html { redirect_to clients_index_path }
format.json { head :no_content }
end
end
_form.html.erb
<%= form_for(#call) do |f| %>
<%= f.label :caller_name %>
<%= f.text_field :caller_name %>
<%= f.label :caller_phone %>
<%= f.text_field :caller_phone, :placeholder => 'xxx-xxx-xxxx' %>
<%= f.label :caller_email %>
<%= f.text_field :caller_email %>
<%= f.button :submit %>
<% end %>
routes.rb
devise_for :users
match 'mdt' => 'mdt#index'
get "home/index"
resources :medics
resources :clients
resources :users
resources :units
resources :mdt do
collection do
put "in_service"
put "en_route"
put "to_hospital"
put "at_hospital"
put "on_scene"
put "out_of_service"
put "at_station"
put "staging"
put "at_post"
put "man_down"
end
end
resources :calls do
member do
post 'close'
end
end
root :to => 'home#index'
devise_scope :user do
get "/login" => "devise/sessions#new"
delete "/logout" => "devise/sessions#destroy"
end

The problem I had was with routes. I needed a post method for a new calls. After creating two actions (one for create and one for destroy) along with their routes everything started working. It looks like it was trying to use the default routes and actions which would re-route to the wrong URL for my purposes.
resources :clients do
collection do
post "calls"
end
member do
delete "cancel"
end
end
def calls
#call = Call.new(params[:call])
if #call.save
redirect_to clients_path, notice: "Call was successfully created."
else
render :new
end
end
def cancel
#call = Call.find(params[:id])
#call.destroy
respond_to do |format|
format.html { redirect_to clients_path }
format.json { head :no_content }
end
end

Related

Wrong controller is active when using an external SQL table.

I am working on a back-office app. The apps I am deploying have a model/table of user_messages. The user messages are used to display admin messages from a central app. The idea is that I can use that app to publish messages to the individual apps such as "System will be unavailable from noon to 1 on Friday".
The individual apps use their own schema in the database. for example, the research library would be rl.user_messages etc.
Since I will need to access multiple tables, I set it up so I can access external tables.
production:
adapter: sqlserver
host: server1
port: 1435
database: web
username: XX
password: xXX
schema_search_path: umc
technical_libraries:
adapter: sqlserver
host: server1
port: 1435
database: XXXX
username: XX
password: XXXXXXXX
schema_search_path: tl
The model that lets me connect to the technical library as an external model is
class TechnicalLibrary < ActiveRecord::Base
self.abstract_class = true
def self.table_name_prefix
'tl_'
end
establish_connection "technical_libraries" # TODO might want to name this to a generic
end
class UserMessage < TechnicalLibrary
self.table_name = "tl.user_messages" # for this one, as opposed to the product development, we need to specify the schema.
end
My technical Libraries controller is
class TechnicalLibrariesController < ApplicationController
def index
#user_messages= TechnicalLibrary::UserMessage.all
end
def show
#technical_library = TechnicalLibrary::UserMessage.first # TODO HARDWIRED -
end
def new
#technical_library = TechnicalLibrary::UserMessage.new
end
def edit
#technical_library = TechnicalLibrary::UserMessage.find(params[:id])
end
def create
#technical_library = TechnicalLibrary::UserMessageRl.new(technical_library_params)
respond_to do |format|
if #technical_library.save
format.html { redirect_to #technical_library, notice: 'Technical library was successfully created.' }
format.json { render :show, status: :created, location: #technical_library }
else
format.html { render :new }
format.json { render json: #technical_library.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #technical_library.update(technical_library_params)
format.html { redirect_to #technical_library, notice: 'technical library was successfully updated.' }
format.json { render :show, status: :ok, location: #technical_library }
else
format.html { render :edit }
format.json { render json: #technical_library.errors, status: :unprocessable_entity }
end
end
end
def destroy
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_technical_library
#technical_library = TechnicalLibrary.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def technical_library_params
params.require(:technical_library).permit(:message, :expires)
end
My technical Libraries form is
<%= form_for(#technical_library) do |f| %>
<% if #technical_library.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#technical_library.errors.count, "error") %> prohibited this technical_library from being saved:</h2>
<ul>
<% #technical_library.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :message %><br>
<%= f.text_field :message %>
</div>
<div class="field">
<%= f.label :expires %><br>
<%= f.datetime_select :expires %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<hr>
Controller <%= controller_name %> | <%= action_name %>
<hr>
The form looks as follows. The submit button seems to be wrong. it is pointing to another model.
If I click on the submit button, I get an error message as follows. I suspect that the problem lies in inheriting from another model.
NameError in UserMessagesController#show
uninitialized constant TechnicalLibrary::UserMessageRl
Rails.root: C:/Users/cmendla/RubymineProjects/user_message_console_3
Application Trace | Framework Trace | Full Trace
app/controllers/user_messages_controller.rb:15:in `show'
Request
Parameters:
{"id"=>"1"}
I had a UserMessage model that I'm probably not going to use since I will connect to the individual application's tables.
class UserMessage < ActiveRecord::Base
end
OK - figured it out. I had to specify the controller and action in the form_for statement.
<%= form_for #technical_library, :url => { :controller => "technical_libraries", :action => "update" }, :html => {:method => :post} do |f| %>
That seems to be doing the trick

Do I need to reload the comment object or the partial that contains the comment in case of using Ajax in Rails 3?

I have been trying to figure out adding comments without reloading the page using Ajax, after reading few different tutorials this is what I came up to so far, and it's not working:
inside user_comments/_comments.html.erb
<div id="comment_form">
<%= simple_form_for [#commentable, #comment], :html => { :multipart => true }, :remote => true do |f| %>
<div class="picture"><%= image_tag current_user.avatar.url(:thumb) %></div>
<%= f.input :content, label: false, :placeholder => "Add Comment", :input_html => { :rows => 4 } %>
<%= f.submit "Add Comment" %>
<% end %>
</div>
Inside the controller:
def create
#users = User.all
#comment = #commentable.user_comments.new(params[:user_comment])
#comment.user_id = current_user[:id]
##commentable.user_comments.create(:user_id => current_user[:id])
if #comment.save
flash[:notice] = "Successfully created comment."
respond_to do |format|
format.html { redirect_to #commentable }
format.js
#format.js #{ render 'create.js.erb' }
end
else
render :new
end
end
and inside the create.js.erb
// Display a Javascript alert
<% if remotipart_submitted? %>
$("#comments_list").append("<%= escape_javascript(render(:partial => 'user_comments/comments')) %>");
<% end %>
I'm using a Gem called: remotipart
I don't know what I'm missing in the process.
in the console I get:
POST http://localhost:3000/assignments/2/user_comments
200 OK
134ms
which means the post goes through, but the comment doesnt get added back to the partial.
Ok after 2 days! I fixed it, here is what I can share and might help:
1- make sure to include the :remote => true to the form that is about to be submitted
2- Check the controller and see what the Create action is being redirected, in my case I changed to this:
def create
#users = User.all
#comment = #commentable.user_comments.new(params[:user_comment])
#comment.user_id = current_user[:id]
##commentable.user_comments.create(:user_id => current_user[:id])
if #comment.save
flash[:notice] = "Successfully created comment."
respond_to do |format|
format.html
format.js {#comments = #commentable.user_comments}
end
else
render :new
end
end
Then make sure the create.js.erb is written properly:
$("#comments_list").empty()
$("#comments_list").append("<%= escape_javascript(render(:partial => 'comments')) %>");
there you go! I hope some creates a proper tutorial for newbies like me :)!

Nested routes and dot in url in Rails

I'm building a simple todo app for some practice. I have projects which has_many tasks and tasks belongs_to projects.
So that I can display url/projects/1/tasks I'm nesting the route:
routes.rb
resources :projects do
resources :tasks
end
In my project show view I have the following form:
Add a task:
<%= form_for [#project, #task] do |f| %>
<%= f.label :Task_name %>
<%= f.text_field :name, :placeholder => "Task Name" %>
<%= f.submit 'Create Task' %>
<% end %>
In my tasks controller I'm doing the following:
def create
#project = Project.find(params[:project_id])
#task = #project.tasks.new(params[:task])
if #task.save
redirect_to projects_path(#project)
else
redirect_to projects_path(#project)
end
end
It seems on task.save when I redirect and pass in the project instance variable it redirects me to http://todoapp.dev/projects.5 (5 being the id of the project) instead of http://todoapp.dev/projects/5.
Could the problem be in my controller with the redirect_to method or possibly the nested route?
I have a basic understanding of Rails routing but could use some advice.
Looks like in the redirect_to in my controller I was using the pluralized version of the path. projects_path(#project) instead of project_path(#project).
def create
#project = Project.find(params[:project_id])
#task = #project.tasks.new(params[:task])
if #task.save
redirect_to project_path(#project)
else
redirect_to project_path(#project)
end
end
This ended up working.

Rails 310 Redirect Loop

I'm going back to write a basic app with projects that have tasks. In my show view of a project I want to list the tasks and also include a form. When I wire this all up I get 310 Redirect loop. It's been a while since I've written anything from scratch so would appreciate some help looking at my code.
controller code:
def show
#project = Project.find(params[:id])
#task = #project.tasks.new(params[:task])
if #task.save
redirect_to #project, :notice => "Task added"
else
render action: :show
end
end
view code:
<%= #project.project_name %>
<%= form_for(#task) do |m| %>
<%= m.label :Task %>
<%= m.text_field :task_name %>
<%= m.button :submit %>
<% end %>
<% #project.tasks.each do |t| %>
<%= t.task_name %>
<% end %>
project.rb
has_many :tasks
task.rb
belongs_to :project
You are redirecting to #project, which is interpreted as meaning, redirect to the show page for #product. But you are calling redirect from the show page, hence the redirect loop:
request routed to show page
find project
task instantiated
task saved
redirect to show (loop back to 2)
Normally you don't create records in show, you do it in create. Any reason you're doing it this way?

Rails 3 - Displaying submit errors on polymorphic comment model

Fairly new to Rails 3 and have been Googling every which way to no avail to solve the following problem, with most tutorials stopping short of handling errors.
I have created a Rails 3 project with multiple content types/models, such as Articles, Blogs, etc. Each content type has comments, all stored in a single Comments table as a nested resource and with polymorphic associations. There is only one action for comments, the 'create' action, because there is no need for the show, etc as it belongs to the parent content type and should simply redisplay that page on submit.
Now I have most of this working and comments submit and post just fine, but the last remaining issue is displaying errors when the user doesn't fill out a required field. If the fields aren't filled out, it should return to the parent page and display validation errors like Rails typically does with an MVC.
The create action of my Comments controller looks like this, and this is what I first tried...
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to(#commentable, :notice => 'Comment was successfully created.') }
else
format.html { redirect_to #commentable }
format.xml { render :xml => #commentable.errors, :status => :unprocessable_entity }
end
end
end
When you fill nothing out and submit the comments form, the page does redirect back to it's appropriate parent, but no flash or nothing is displayed. Now I figured out why, from what I understand, the flash won't persist on a redirect_to, only on a render. Now here's where the trouble lies.
There is only the 'create' action in the comment controller, so I needed to point the render towards 'blogs/show' (NOTE: I know this isn't polymorphic, but once I get this working I'll worry about that then). I tried this in the "else" block of the above code...
else
format.html { render 'blogs/show' }
format.xml { render :xml => #commentable.errors, :status => :unprocessable_entity }
end
Anyway, when I try to submit an invalid comment on a blog, I get an error message saying "Showing [...]/app/views/blogs/show.html.erb where line #1 raised: undefined method `title' for nil:NilClass."
Looking at the URL, I think I know why...instead of directing to /blogs/the-title-of-my-article (I'm using friendly_id), it's going to /blogs/the-title-of-my-article/comments. I figure that extra "comments" is throwing the query off and returning it nil.
So how can I get the page to render without throwing that extra 'comments' on there? Or is there a better way to go about this issue?
Not sure if it matters or helps, but the route.rb for comments / blogs looks like this...
resources :blogs, :only => [:show] do
resources :comments, :only => [:create]
end
I've been plugging away at this over the last few weeks and I think I've finally pulled it off, errors/proper direction on render, filled out fields remain filled in and all. I did consider AJAX, however I would prefer to do it with graceful degradation if at all possible.
In addition, I admit I had to go about this a very hacky-sack way, including pulling in a way to pluralize the parent model to render the appropriate content type's show action, and at this stage I need the code to simply work, not necessarily look pretty doing it.
I KNOW it can be refactored way better, and I hope to do so as I get better with Rails. Or, anyone else who thinks they can improve this is welcomed to have at it. Anyway, here is all my code, just wanted to share back and hope this helps someone in the same scenario.
comments_controller.rb
class CommentsController < ApplicationController
# this include will bring all the Text Helper methods into your Controller
include ActionView::Helpers::TextHelper
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to(#commentable, :notice => 'Comment was successfully created.') }
else
# Transform class of commentable into pluralized content type
content_type = find_commentable.class.to_s.downcase.pluralize
# Choose appropriate instance variable based on #commentable, rendered page won't work without it
if content_type == 'blogs'
#blog = #commentable
elsif content_type == 'articles'
#article = #commentable
end
format.html { render "#{content_type}/show" }
format.xml { render :xml => #commentable.errors, :status => :unprocessable_entity }
end
end
end
private
# Gets the ID/type of parent model, see Comment#create in controller
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
end
articles_controller.rb
class ArticlesController < ApplicationController
def show
#article = Article.where(:status => 1).find_by_cached_slug(params[:id])
#comment = Comment.new
# On another content type like blogs_controller.rb, replace with appropriate instance variable
#content = #article
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #article }
end
end
end
show.html.erb for articles (change appropriate variables for blog or whatever)
<h1><%= #article.title %></h1>
<%= #article.body.html_safe %>
<%= render :partial => 'shared/comments', :locals => { :commentable => #article } %>
shared/_comments.html.erb (I'm leaving out the displaying of posted comments here for simplification, just showing the form to submit them)
<%= form_for([commentable, #comment]) do |f| %>
<h3>Post a new comment</h3>
<%= render :partial => 'shared/errors', :locals => { :content => #comment } %>
<div class="field">
<%= f.label :name, :value => params[:name] %>
<%= f.text_field :name, :class => 'textfield' %>
</div>
<div class="field">
<%= f.label :mail, :value => params[:mail] %>
<%= f.text_field :mail, :class => 'textfield' %>
</div>
<div class="field">
<%= f.text_area :body, :rows => 10, :class => 'textarea full', :value => params[:body] %>
</div>
<%= f.submit :class => 'button blue' %>
<% end %>
shared/_errors.html.erb (I refactored this as a partial to reuse for articles, blogs, comments, etc, but this is just a standard error code)
<% if content.errors.any? %>
<div class="flash error">
<p><strong><%= pluralize(content.errors.count, "error") %> prohibited this page from being saved:</strong></p>
<ul>
<% content.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
I slightly refactored #Shannon answer to make it more dynamic. In my 'find_parent' method I'm grabbing the url path and fetching the controller name. In the 'create' method I'm creating an 'instance_variable_set' which creates a dynamic variable for either Articles (#article) or Blogs (#blog) or what ever it may be.
Hopefully you'll like what I've done? Please let me know if you have any doubts or if something can be improved?
def create
#comment = #commentable.comments.new(params[:comment])
if #comment.save
redirect_to #commentable, notice: "Comment created."
else
content_type = find_parent
instance_variable_set "##{content_type.singularize}".to_sym, #commentable
#comments = #commentable.comments
render "#{content_type}/show"
end
end
def find_parent
resource = request.path.split('/')[1]
return resource.downcase
end
You're getting an error because the blogs/show view likely refers to the #blog object, which isn't present when you render it in the comments controller.
You should go back to using the redirect_to rather than render. It wasn't displaying a flash when you made an invalid comment because you weren't telling it to set a flash if the comment wasn't saved. A flash will persist till the next request.