I have the following code as a controller action:
def create
render :js => "alert('hello')"
end
But when I go to this view, I get a missing template error – 'create.rhtml'. What is the correct way to render a javascript response in Rails 1.2.6?
render :file is probably your best bet with Rails that old. You can also use the old RJS style.
Related
as a Ruby newbie I am still getting to grips with the language. I have created a broadcast controller for a simple database that is already being used in production. However, I am getting the above mentioned error. Below is the code I have used:
show.html.erb
<p id="notice"><%= notice %></p>
<%= link_to 'Edit', edit_broadcast_path(#broadcast) %> |
<%= link_to 'Back', broadcasts_path %>
Index.html.erb
index.html.erb
broadcasts_controller.rb
boradcast controller
help controller
class HelpController < ApplicationController
skip_before_action :authenticate_user!
def about
#render text: "Hello"
end
end
I am not sure if I am missing any files or configs, I will add them in the comments if need be. Thanks
Incoming requests may use headers or parameters to indicate to Rails what format, called "MIME type", the response should have. For instance, a typical GET request from entering a URL into your browser will ask for an HTML (or default) response. Other types of common responses return JSON or XML.
In your case your "about" action does not have any explicit responders, and because of that Rails can't match the requested format (which is what the error message is trying to convey). You will probably just want to add an HTML template app/views/help/about.html.erb with your content. Rails should identify the HTML template and handle things from there.
More info
In Rails you need to respond with a specific format, and it is easy to setup your controller actions to handle a variety of formats.
Here is a snippet you might find in a controller which can respond in 3 different ways.
respond_to do |format|
format.html { render "foo" } # renders foo.html.erb
format.json { render json: #foo }
format.xml { render xml: #foo }
end
You can see more examples and deeper explanations in the documentation here.
ActiveRecord helps because it comes with serializers out of the box which can create JSON and XML representations of your objects.
My question is : do we need a view file for each action in our controller?
(like if we defined a say_hello action in a controller, is it necessary to add say_hello.html.erb in his view directory?
I'll edit this to say it depends (with same content). If you plan on using that controller action as JS or JSON you don't need a view file. if you want one to share in multiple views, the file can contain a shared partial (which can be used in other views). This examples is shown by the generators scaffolding create examples like this. They are helpful if you are learning rails. Not great otherwise.
If you were to share a partial, you could have a partial named _form.html.erb and then inside your say_hello.html.erb file, it would just call:
<%= render 'form' %>
If you want to render JSON or JS files you can respond_to in your action:
respond_to do |format|
format.html # say_hello.html.erb
format.json { render json: #hello } #no file needed
format.js { render js: #hello }
#format.js {} #do nothing... or use a little javascript in there...
# or have a file named say_hello.js.erb and use your #hello variable
end
Edit:
One last update. Your say_hello.js.erb file can do the anything on another view (if called remotely):
say_hello.js.erb
<% if #hello.attribute == "some value" %>
$('#div_in_another_view').show();
<% else %>
$('#div_in_somewhere_else').hide();
<% end %>
You can do jQuery and anything you want to the view calling it (as long as it's using AJAX).
End edit
Guides are great place to get started. Railscasts.com as well (even though Ryan isn't updating anymore).
Edit: A great example on the different options on the respond_to is on this rails guide regarding javascript
You can just pass javascript straight from that format.js call, or use a file if you need more complicated stuff. You don't need to do anything also. You could just have it return xml or nothing as well, depending on your use case.
No, it is not required. For example, you can render json or xml data from the controller without needed a view at all. This article explains it very well http://guides.rubyonrails.org/layouts_and_rendering.html
No you do not need a view for each action. BUT you do need a view for each action that will reach the end of the method.
If you return anywhere in the action then you are fine. A view is only required when an implicit render is called due to execution reaching the end of the action.
No, it's really up to you and it depends on what the action will actually do. Actions can render different types content types: text, json, html, xml... etc. Here's an example:
def show
render xml: #something
end
This action doesn't have a view, but it'll output an xml when called. It can also render different things based on the format of the call:
def show
respond_to do |format|
format.html do
redirect_to '/'
end
format.json do
render xml: #something
end
end
end
The action may also redirect (again, this one doesn't have a file):
def show
redirect_to '/'
end
At the end, it's really up to the programmer to handle how the action behaves, but if you leave it empty, it'll assume there's a file to render.
I haven't been able to find any useful resources online on how to do this. Basically what I'm trying to do is run a simple jQuery $('#test-div').show(); when my def show_div controller action is complete.
I've tried the following and it doesn't work. It actually renders HTML which is confusing to me. when I explicitly state that the method respond with js.
users_controller.rb
def show_div
#user = User.first
respond_to do |format|
format.js {}
end
# also tried
# render :js => "$('#test-div').show();"
end
show_div.js.erb
$('#test-div').show();
render :text should do what you are asking for -- just return raw text (which in your case happens to be JavaScript code) without doing anything to it.
I'm trying to learn how to use AJAX in my rails apps so i've decided to start with something simple. I have a blog app on which user can vote on any blog post. Here is my code for posts#vote:
posts_controller.rb
class PostsController < ApplicationController
(...)
def vote
post = Post.find(params[:id])
if current_user.voted_on?(post)
current_user.unvote_for(post)
else
current_user.vote_for(post)
end
respond_to do |format|
format.html { redirect_to post_path(post) }
format.js
end
end
end
and here is a link code for my posts#view:
view.html.erb
<%= link_to "Vote", vote_post_path(post.id), :remote => true %>
And now, if i'll click my Vote link, posts#vote action works and vote is casted, however i'm getting an error:
ActionView::MissingTemplate (Missing template posts/vote,
application/vote with {:handlers=>[:haml, :coffee, :erb, :builder],
:locale=>[:en], :formats=>[:js, :html]}.
I have (empty) vote.rjs file in my views/posts folder but for some reason rails can't see it. According to error, the only file extensions that rails is searchng for are .haml, .coffee, .erb and .builder. Shouldn't there be also a .rjs extension on that list? Thanks in advance.
Your file should be called vote.js.erb. Rails doesn't use a .rjs extension.
The .rjs extension was originally used for Rails and Prototype JS library.
With Rails 3.1 the default library was switched to JQuery.
If you want to use .rjs in your Rails project it would mean using Prototype instead of JQuery. The gem for that is prototype-rails.
I'm working with rails 3.1.0 and this is my first application on 3.1.0
I have a remote link:
link_to "my link",{:controller=>"my_controller",:action=>"my_action"},:remote=>true
and in my_controller I have
def my_action
#data = Data.all
render :update do |page|
page.replace_html "show_data",:partial=>"data_partial"
end
end
but then in the log I get an error
ActionView::MissingTemplate (Missing template my_controller/update...
and I was checking at this post
http://wowkhmer.com/2011/09/19/unobtrusive-ajax-with-rails-31/
do I really need to use a coffee script or a js.jrs to do this thing ??
Javascript integration doesn't work this way anymore. render :update ... tries to render the update action, which doesn't have an associated template. You need to move that out of the controller and into the view code, in app/views/my_controller/my_action.js.erb:
$("show_data").update("<%= escape_javascript(render :data_partial) %>");