I have a 'like'-counter in a rails project. Whenever one clicks this 'like'-link I want to add one to the like_counter in the database. The logic works well and the database is updated, but I cannot figure out how to set up the Ajax Request correctly so it refreshes the page or the div when completed.
In my view this looks as follows:
<%= link_to_remote 'like', :url => {
:controller => 'projects',
:action => 'like_it',
:id=> #project.id }%>
The controller:
def like_it
#project = Project.find(params[:id])
#project.update_like
render :update do |page|
page.reload
end
end
the update_like method is in the model and just adds one to the counter and saves the project (this part works).
As for the page.reload I Firefox throws an RJS-Error: ReferenceError: Reload is not defined. And the page is not reloaded
What do I do wrong? Is there a more distinguished way to just reload the div containing the counter? Any help is much appreciated!
Try:
render :update do |page|
page << "window.location.reload()"
end
Related
This is the first time I've encountered this problem.
I have a view which submits a post request to a controller which updates two tables.
def update
if request.post?
if #circuit
# update
#circuit.update_attributes params[:circuit]
#logical_interface = LogicalInterface.new params[:logical_interface]
#logical_interface.save
#redirect_to :action => 'update', :id => #circuit.id
#success = "Updated." if #circuit.valid?
else
# attempt create
end
end
end
These three lines are what I've added to the controller:
#logical_interface = LogicalInterface.new params[:logical_interface]
#logical_interface.save
redirect_to :action => 'update', :id => #circuit.id # this was added because the view wasn't being updated until refreshed
If I keep the redirect, the view will be updated accordingly but I get no Updated. message in the #success variable.
If I comment out the redirect, the circuit form fields at the top of my form will update but not the table of logical_interfaces that I am adding to but I still get the Updated. success message. Everything is in the view directly, no partials are used.
Hopefully I've explained it properly but if anyone is unsure then I can update the question to go into more detail.
The form is just:
<%= form_tag :controller => "circuit", :action => "update" %>
...
</form>
In the form I use two objects circuit and logical_interface to split up the inputs so that in the controller I can update the circuit and create a new logical_interface.
try to adjust positions of redirect_to and #success, I think redirect_to should be the last line of the block.
And If you use redirect_to, you will lose all your instance variables, so better way is using flash.
in your controller:
flash[:notice] = "Updated." if #circuit.valid?
redirect_to :action => 'update', :id => #circuit.id
in your page:
<p><%= flash[:notice]%></p>
Main page of my website consists of multiple blocks such as last offers, last news, last articles and so on. Each block has controls like "show more" or "refresh" so that when user clicks, the block should refresh or update it's own content through ajax.
Also when a page is loaded the first time, it should already be filled with content (for disabled javascript and search engines).
What's the best, dry, rails-way to build such structure?
That's In my articles_controller.rb:
def line
#articles = Article.filter(params)
respond_to do |format|
format.html { render :layout => false, :partial => "articles/line.html", :locals => {:articles => #articles} }
format.json { render :json => { "html" => render_to_string(:partial => "articles/line.html", :locals => {:articles => #articles}) } }
end
end
When I call /articles/line through ajax it sends json that contains cut of html-code, and all that remains is to append it to a specified div. This works. When I call /articles/line directly it also works and displays required partial of html-code.
But what should I write in my main_controller (it should collect and render all blocks from different controllers)? Where should I write some blocks settings (for example, quantity of records and offset, they required both in static and ajax cases)?
Most convenient for me is to set everything up right in the view template of main page, like that:
<div id="last-news" data-params="{offset:0,limit:5}">
<%= render #here we get html from :controller => news, :action => list, :params => get them from parent div %>
</div>
<div id="last-articles" data-params="{offset:0,limit:10}">
<%= render #here we get html from :controller => articles, :action => list, :params => get them from parent div %>
</div>
But that doesn't look like MVC.
I'm new to using AJAX in Rails (I know... I know...), and am positive that I'm doing something wrong that's probably just the wrong call or something. But I've hunted and can't seem to find it.
Anyway, I'm rendering out quick partial (this is working right) and then I want to refresh it with an AJAX call. Here's what I thought would work:
<div id="two_on_two"><%= render :partial => "quickread" %></div>
<p><%=link_to_remote "load two new stories", :url => {:partial => 'quickread'}, :update => 'two_on_two' %></p>
that just blows out the page (a quick flash and then just a blank browser window). If I switch from :partial to :action in that AJAX call, then it dynamically loads a "template missing" in that two_on_two div.
Clearly, there's something easy I'm missing here, right?
Thank you so much!
First, read api:
http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/link_to_remote
You should specify your url correctly (controller, action, other params, not partial!) and define your RJS in controller action.
IE:
index.html.erb
<div id='two_on_two'></div>
link_to_remote 'Link Name', :url => {:controller => "bar", :action => "baz"}
bars_controller.rb
def baz
respond_to do |format|
format.js{ render :update do |page|
page.replace_html 'two_on_two', 'Hello world!'
end}
end
end
So when you will click Link Name, in your two_on_two div will appear "Hello world text".
I am trying to display an error message of flash in Ajax using Rails but it doesn't display it, and I have tried several ways to do it but I just can't get it right.
Here is my form to display my errors:
#flash-error.flash-error{:style => "display: none"}
#flash-notice.flash-info{:style => "display: none"}
%h3 New Document
- form_for(:repo_document, :url => {:all_categories => #repo_categories, :action => "create", :format => "js", :query => params[:query]}, :html => { :id => "repo_document_form", :multipart => true, :target => 'upload_frame'}) do |form|
Here is the controller:
if !params[:stands]
respond_to do |format|
format.js do
responds_to_parent do
render :update do |page|
page.show "flash-error"
page.replace_html "flash-error","Please select stands you want to grant permission to view this stand."
end
end
end
return
end
end
What am I doing wrong?
js.rjs to the rescue
def action
#true = params[:stands]
respond_to |format|
format.js
end
end
in action.js.rjs:
if #true
# do true stuff
else
page.replace_html 'error_block_dom_id', :text => 'This is my error'
end
and the original view file that you make the ajax call from:
#nothing here due to no errors - errors will appear if they happen
<div id="error_block_dom_id"></div>
No overarching reason to use the flash - just update a DOM object with the error content.
A possible solution would be to send an ajax call to an action in a controller and set your flash messages in that action
Flash is only going to display on the next time the page is loaded. It doesn't update through AJAX. One of the caveats of AJAX is that it doesn't deal with file uploads...
See this for more details; http://guides.rubyonrails.org/form_helpers.html#uploading-files
I think the problem might be elsewhere: Element's method show (call of which is generated when You call page.show "flash-error") will not remove display: none css style when it is given inside the external Css file. This is a quotation from older version of Prototype's API Documentation.
So try to add display: none as inline style of Your div's. I hope it will help!
How can I render after executing an action in a restful controller instead of redirecting.
I have a controller with standard actions, and I added a special action that adds data to the resource in question, via a form on the #show page (Think comments on a post). I am validating the input from the form and want to re-render the show action on error and redirect to the show action on success.
I want to render to save the user from inputting their info twice, but when I try to render the show action with an error in the flash[:notice] I get an error saying that I am not specifying an ID. When I do specify an ID, it tries to render a new template that doesn't exist yet.
I am thinking that it should be a as simple as:
def add_comment
if my_validation?
save the object
redirect_to :action => "show", :id => params[:id]
else
render :action => "show", :id => params[:id]
end
end
This is not my actual code, just something I put together just now as an example.
The best way is to re-render the :new
def create
#obj = TheObject.new(params[:object])
render :action => :new unless #obj.save
end
And in the new.html.erb
<% form_for :obj,
:url => object_url(#obj), :html => {:method => :post} do |f| %>
<%= f.text_field :name %>
<% end %>
That way, the inputs in the form will be pre-filled with what the user entered.
Create a new data object and add the values from the form, before you rerender, think it would work then. If you still get problems, try setting a boolean for editing new vs. existing rows, or create two different views entirely.
I've done it before but I don't quite remember how. Sometimes when I used the very typical use of the MVC pattern, it was allmost "automagical", othertimes (as I had to use an old quirky database) I had to code all the magic myself; sometimes usin the .new? function (or what it was called) on the ActiveRecord object, othertimes I used temporary "magic values" for ID (typically alphabetic strings for invalid id values.
(I appologize if I made some mistakes, it's a while since I coded Rails code...)