Variable in View is always nil - ruby

I am new to ruby. I created a new action in controller where I set variable test1
def tsload
#test1 = '00:00'
respond_to do |format|
format.html {
render :template => 'tsload'
}
end
end
But in my View the value of variable test1 is always nil. It seems that it is undefined.
<p>Test</p>
<% if #test1.nil? %>
<p>nil</p>
<% end %>
I do not understand what is wrong. In older actions in my controller everything works OK. Can anyone please help me?
This is line from my routes.rb
match 'wktime/tsload', :to => 'wktime#tsload', :via => [:get]

Related

How to pass param from 1 controller to another

I want to pass param from the following link in the view of Client controller
and the hash is #client, I want to pass #client.user_id, if i put (:id => #client.user_id) I am not able the get :id in the other controller Estate where I want to pass this param. What should I do ? Is there a way to do it ?(Two controllers are Client and Estate, I want to pass param from Client view to the Estate controllers create method. There is no nesting of resources here!)
<%= link_to "New Property", new_estate_path(:key => #client.first.user_id) %>
create action
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(params[:key])
debugger
#estate = serve.estates.build(params[:estate])
##estate.user_id = user_id
debugger
end
respond_to do |format|
if #estate.save
if #estate.Mgmt.nil?
EstateMailer.company_confirmation(#estate).deliver
end
format.html { redirect_to #estate, notice: 'Estate was successfully created.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
The code you pasted here should work:
<%= link_to "New Property", new_estate_path(:id => #client.user_id) %>
I think the problem is, you are expecting the params in create method but where as it actually goes to new method.
If you are looking for the create method. You can do
<%= link_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
But that is not the right approach to use for POST actions. The right solution would be to use button_to.
<%= button_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
link_to defaults to GET and button_to defaults to POST, as those are their primary usages. You can override :method if you want them to perform other action than their default.
Simply do this
<%= link_to "New Property", new_estate_path(user_id: #client.user_id) %>
In your controller:
params[:user_id]
You problem is that the create action is a POST not a GET. The link_to will only allow GET actions.
I made class variable in the controller outside all the actions.
##key, and in the new action assigned ##key the user_id that was coming through the params, and this ##key in the create action. I don't know if its the right way to do it. But it worked like a charm !

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 3 -rendering partials and error "undefined local variable or method"

I have a photos in gallery (PhotosController) and I wanna add to every photo a comments. Into the statement of photos I added a partial for rendering comments + form for adding new comment.
My problem is, that when I send the form with a new comment, so I'll get the rendering error:
**NameError (undefined local variable or method `photo' for #<CommentsController:0x00000100ce0ad0>)**:
This is how looks my code:
views/photos/index.html.erb
<%= render #photos %>
views/photos/_photo.html.erb
<div><%=image_tag photo.photo.url(:thumb)%></div>
<div class="comments_to_photo">
<%= render :partial => 'photos/photo_comments', :locals => { :photo => photo }%>
</div>
photos/photo_comments
<%photo.comments.each do |cmnt|%>
<div><%=cmnt.comment%></div>
<%end%>
<%=form_tag comment_path, :remote => true do %>
<div><%=text_area_tag 'comment[comment]'%></div>
<%=submit_tag%>
<%end%>
controllers/CommentsController
def create
#comment = Comment.new(params[:comment])
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.js {
render :partial => '/photos/photo_comments', :locals => { :photo => photo } do |page|; page << "$(this).html('abcde');" end
}
else
format.html { render action: "new" }
format.js
end
end
end
I would like to refresh the form and comments statement in the photo, where was added a comment. Could anyone help me, please, how to avoid the error above?
Thank you in advance
EDIT: I added for refresh comments through AJAX the file _photo_comments.js.erb:
$('#photo_comment').html("<%= escape_javascript(render('photos/photo_comments')) %>");
And I get the error
ActionView::Template::Error (stack level too deep):
activesupport (3.2.1) lib/active_support/notifications/instrumenter.rb:23
with tens of this line:
Rendered photos/_photo_comments.js.erb (562.2ms)
and the last one
Completed 500 Internal Server Error in 580ms
What's wrong with rendering? I can't render partial html file from partial JS file?
In your controller you have:
:locals => { :photo => photo }
but the variable photo doesn't exist there. It should be:
:locals => { :photo => #comment.photo }
image_tag photo.photo.url(:thumb) <- Is it what you want to have photo.photo ?

RoutingError when using jQuery UI tabs with ajax

I'm getting ActionController::RoutingError in Profiles#show when I click a link to render a layout as part of my implementation of jQuery UI tabs. Here's my link_to:
<%= link_to "Messages", :controller => 'profiles', :action => 'profile_messages', :remote => true %>
My ProfilesController:
def profile_messages
#messages = User.find(#profile.user_id).messages
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end
My profile_messages erb layout:
<div id="tabs-2">
<% for message in #user.messages %>
<div class="message-1">
</div>
<% end %>
</div><!-- end messages -->
Routes.rb:
resources :messages do
get "messages/profile" => :profile_messages
resources :responses
end
What I want to happen is: when you click the link created by my link_to, the layout in profile_messages.html.erb shows and loads the messages in that specific layout. What's going on here?
UPDATE: Adding the new line in Routes.rb gives me a new route:
message_messages_profile GET /messages/:message_id/messages/profile(.:format) {:action=>"profile_messages", :controller=>"messages"}
So I tried this in my Profiles show.html.erb I put:
<li><%= link_to "Messages", message_messages_profile_path, :remote => true %></li>
This gives me a RoutingError in Profiles#show -- No route matches {:action=>"profile_messages", :controller=>"messages"}. Even when I add the following into my MessagesController:
def profile_messages
#message = #user.messages.find(params[:user_id])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end
get "messages/profile" => "messages#profile_messages", :as => profile_messages
resource :messages do
resource :responses
end
You don't have a route for that controller action. Rails doesn't map ":controller/:action/:id" by default any more. You can also just enable that route if you want. You could be able to reference this via profile_messages_path.
It's assuming 'show' is actually an id for messages here I think. The default routes for a resource are listed here: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions. Make sure you list your routes first!
resource :messages do
collection do
get :profile_messages
end
end
in your view
<li><%= link_to "Messages", "/messages/profile_messages", :remote => true %></li>
Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code:
Exclude application layout in Rails 3 div
Rails 3 jQuery UI Tabs issue loading with Ajax

Rails 3 and Ajax confusion

In short, I don't understand ajax with rails. I did this tutorial a little while ago and I can get it to work. No problems. The problems seem arise when I have more than one model.
For example, if I have a model "cats", I use the tutorial to implement some ajax, works nicely - each time I add a new cat to the list, it appears at the top without reloading the page. Then I add a "dogs" model, and I render the _dog.html.erb file in the cats index and call on it with something like #dogs.each do |dog| etc.
Now I need to implement the ajax for the dogs, but do I put the ajax files into create.js.erb in the dogs folder or in the cats create.js.html folder? I've tried both, no success. The first model, in this example cats, will continue to work, but the others don't. I know that its half working because the page doesn't reload when I hit enter, but nothing is generated either. I've checked the id's, all correct.
Is there anything else I should be looking for? My logic says that if i'm in the cats index and rendering something from _dog.html.erb, I should put all the create ajax in the cats create.js.html folder….
Help is more than appreciated.
Also, just as a small second question, I read another tutorial and it advised me to delete everything in the public/javascripts folder except "application.js", which in my case is blank. I haven't because ajax is working, just not for the other models. Should I take the tutorials advise?
Thanks again.
Update
This is the code from "show" in the cats controller.
#dog = Dog.new
respond_to do |format|
format.html
end
Update 2
Ok, so "Cats" is really "Games", and "Dogs" is really "Features". I used the cats and dogs examples because I thought in theory it would be easier, sorry if it made it more confusing :).
The code - the ajax for creating games in the games index is working, but the ajax for creating features in the games show is not. The games show is where I want to create new features using ajax. the features are created but only viewable after a page reload.
class GamesController < ApplicationController
def index
#games = Game.paginate(:page => params[:page], :per_page => 10)
#game = Game.new
respond_to do |format|
format.html
end
end
def show
#user = User.find(params[:id])
#gameid = Game.find(params[:id])
#features = Feature.paginate(:page => params[:page], :per_page => 8, :conditions => {:game_id => #gameid})
#feature = Feature.new
respond_to do |format|
format.html
end
end
def create
#game = Game.new(params[:game])
respond_to do |format|
if #game.save
format.html { redirect_to(games_url,
:notice => 'game was successfully created.') }
format.js
else
format.html { redirect_to(games_url) }
end
end
end
def destroy
#game = Game.find(params[:id])
#game.destroy
respond_to do |format|
format.html { redirect_to(games_url) }
format.js
end
end
end
class FeaturesController < ApplicationController
def index
#features = Feature.all
#feature = Feature.new
respond_to do |format|
format.html
end
end
def show
end
def create
#feature = Feature.new(params[:feature])
respond_to do |format|
if #feature.save
format.html { redirect_to(features_url,
:notice => 'feature was successfully created.') }
format.js
else
format.html { redirect_to(features_url) }
end
end
end
def destroy
#feature = Feature.find(params[:id])
#feature.destroy
respond_to do |format|
format.html { redirect_to(features_url) }
format.js
end
end
end
(features/create.js.erb)
$('#features').prepend('<%= escape_javascript(render(#feature)) %>');
$('#features > li:first').effect('highlight', {}, 3000);
$('#features_form > form')[0].reset();
(games/create.js.erb)
$('#games').prepend('<%= escape_javascript(render(#game)) %>');
$('#games > li:first').effect('highlight', {}, 3000);
$('#game_form > form')[0].reset();
(games/index)
<h1>Games</h1>
<table>
<tr>
<td class="main">
<ul id="games">
<% #games.each do |game| %>
<%= render 'game', :game => game %>
<% end %>
</ul>
<% if signed_in? %>
<div id="game_form">
<%= render 'form' %>
</div>
<% else %>
<% end %>
</td>
<td class="sidebar">
</td>
</tr>
</table>
(games/show)
<h1>Features</h1>
<table>
<tr>
<td class="main">
<h2>Features</h2>
<div id="features_form">
<%= render 'features/form' %>
</div>
<ul id="features" style="margin:0;padding:0;">
<% #features.each do |feature| %>
<%= render 'features/feature', :feature => feature %>
<% end %>
<%= will_paginate #features, :class => 'pagination' %>
</ul>
</td>
<td class="sidebar">
</td>
</tr>
</table>
Ok, I got it to work. All that was missing was format.js under the format.html in show in the games controller. Like this:
def show
#user = User.find(params[:id])
#gameid = Game.find(params[:id])
#features = Feature.paginate(:page => params[:page], :per_page => 8, :conditions => {:game_id => #gameid})
#feature = Feature.new
respond_to do |format|
format.html
format.js
end
end
I guess the strange thing is that games didn't need this to execute ajax...
Cheers guys for the help

Resources