Here is my simple ajax code.
The request is made, I get the response but my view does not get rendered with new data. I get a new page with new html that I asked to render instead being rendered inside current page.
controller -
def list
#users = User.find(:all)
end
def show
respond_to do |format|
format.html { render :partial => "ajaxshow" }
format.js
end
end
view -
<% #users.each do |c| %>
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
<% end %>
partial -
# cat _ajaxshow.html.erb
<div align="left" id="user_ajax">
<table width="1000px">
<tr><th>User ID</th><th>First</th><th>Last</th><th>ID</th><th>Email</th></tr>
</table>
log -
Started GET "/users/show?remote=true&user_id=someuser" for 10.10.10.10 at 2012-04-17 04:01:09 -0400
Processing by UsersController#show as HTML
Parameters: {"remote"=>"true", "user_id"=>"someuser"}
Rendered users/_ajaxshow.html.erb (0.3ms)
Completed 200 OK in 2ms (Views: 1.3ms | ActiveRecord: 0.0ms)
Your link_to will not trigger the ajax call
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
First change the above code
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id }, { :remote => true, :method => :get } %>
You need to have a .js.erb file for the User controller action which will be called through the format.js call.
In show.js.erb use
$('#some_div_id').html($('<%= render :partial => "ajaxshow" %>'))
Anyhow the purpose of your action seems obscure to me.
Related
Hello I'm new to rails 4
I am working on project where we can post and rate it. I have used activerecord reputation gem. I have been following the http://railscasts.com/episodes/364-active-record-reputation-system video.
I am stuck at the routing point. When I click on upvote or downvote it shows me error.
my routes.rb file has
resources :posts do
resources :comments, :only => [:create]
member { post :vote }
end
get "posts/create"
get "posts/destroy"
get "posts/new"
get "posts/index"
get "posts/show"
get "posts/edit"
get "posts/update"
_post.html.erb
<h4 class="timeline-title"><%= link_to_unless_current post.title, post %></h4>
<p> Created : <%= post.created_at.strftime("%d/%m/%Y") %> by <%= post.postedby %>
</p>
<% if current_cubestudent.email == post.postedby %>
<p><%= link_to 'Edit', edit_post_path(#post) %>
<%= link_to 'Destroy', posts_path, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<%= simple_format post.body , :class => "timeline-body"%>
<%= pluralize post.reputation_for( :votes).to_i, "vote" %>
<% if current_cubestudent && !current_cubestudent.voted_for?(post) %>
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
<%= link_to "down", vote_post_path(post, type: "down"), method: "post" %>
<% end %>
my post#show is
<%= stylesheet_link_tag "application",:media =>"screen" %>
<p id="notice"><%= notice %></p>
<p id="alert"><%= alert %></p>
<%= render :partial => #post %>
<%= link_to 'Back', posts_path %>
<h2 id="timeline">Comments</h2>
<div>
<%= render :partial => #post.comments %>
</div>
<div class="container">
<%= form_for [#post, Comment.new] do |f| %>
<div style="padding-bottom:0">
<%= f.text_area :body , :placeholder => "Write your comment"%>
<%= f.submit "Add comment", :class => "btn btn-info" %>
</div>
<% end %>
</div>
posts controller is
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def create
#post = Post.new(post_params)
#post.postedby = current_cubestudent.email
#post.postedbyid = current_cubestudent.id
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: #post }
else
format.html { render action: 'new' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
def new
#post = Post.new
end
def index
#posts = Post.find_with_reputation(:votes, :all, order: "votes desc")
end
def show
#post = Post.find(params[:id])
end
def edit
end
def update
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def vote
value = params[:type] == "up" ? 1 : -1
#post = Post.find(params[:id])
#post.add_or_update_evaluation(:votes, value, current_cubestudent)
redirect_to :back, notice: "Thank you for voting"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :body, :subject)
end
end
after rake routes | grep post
C:\Sites\project>rake routes | grep post
post_comments POST /posts/:post_id/comments(.:form comments#create
vote_post POST /posts/:id/vote(.:format) posts#vote
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
posts_create GET /posts/create(.:format) posts#create
posts_destroy GET /posts/destroy(.:format) posts#destroy
posts_new GET /posts/new(.:format) posts#new
posts_index GET /posts/index(.:format) posts#index
posts_show GET /posts/show(.:format) posts#show
posts_edit GET /posts/edit(.:format) posts#edit
posts_update GET /posts/update(.:format) posts#update
Can someone help me on it....??
Your main problem is in this code
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
you would like to send "post" request but in fact you send default ("get") request.
I can suppose that link_to accepts only symbols for method (you pass string). So try this
<%= link_to "up", vote_post_path(post, type: "up"), method: :post %>
Another source of the problem can be wrong routes. If code above does not help you run in console rake routes | grep post and add output to the question.
I try a bit of ajax first time but did not get success, i want to render a partial on radio button select using ajax, here is my code :
My script.js:
$(document).ready(function(){
$.ajax({
url : "/income_vouchers/income_voucher_partial?$('form input[type=radio]:checked').val()="+$('form input[type=radio]:checked').val(),
type: "GET",
data: {
type: $('form input[type=radio]:checked').val()
}
});
});
income_voucher.js.erb
$("#payment_mode").append('
<% if params[:type]== 'cheque' %>
<%= escape_javascript render :partial => "cheque" %>
<% elsif params[:type]=='card' %>
<%= escape_javascript render :partial => "card" %>
<% elsif params[:type]=='ibank'%>
<%= escape_javascript render :partial => "ibank" %>
<% else params[:type] == 'cash' %>
<% end %>
');
My from:
<script type="text/javascript" src="/javascripts/voucher.js"></script>
<%= form_for(#income_voucher) do |f| %>
<%= render 'shared/form_error', :object => #income_voucher %>
<div >
<%= radio_button_tag :transaction_type,'cash', :checked => true %>
<%= f.label :transaction_type, "Cash", :value => "cash" %>
<%= radio_button_tag :transaction_type,'cheque' %>
<%= f.label :transaction_type, "Cheque", :value => "cheque" %>
<%= radio_button_tag :transaction_type,'card'%>
<%= f.label :transaction_type, "Card", :value => "card" %>
<%= radio_button_tag :transaction_type,'ibank'%>
<%= f.label :transaction_type, "Internet Banking", :value => "ibank" %>
</div>
<div id = "payment_mode">
<% if params[:type]== "cheque" %>
<%= render :partial => "cheque", :f => f %>
<% elsif params[:type]=='card' %>
<%= render :partial => "card", :f => f %>
<% elseif params[:type] == 'ibank'%>
<%= render :partial => "ibank", :f => f %>
<% else params[:type] == 'cash' %>
<% end %>
</div>
<%= f.submit %>
<% end %>
and here is my controller method:
class IncomeVouchersController < ApplicationController
def new
#income_voucher = IncomeVoucher.new
#invoices = current_company.invoices
#income_voucher.build_payment_mode
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #income_voucher }
end
end
def create
#income_voucher = IncomeVoucher.new(params[:income_voucher])
transaction_type = params[:transaction_type]
payment_mode = nil
if transaction_type == 'cheque'
payment = ChequePayment.new(params[:cheque_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'card'
payment = CardPayment.new(params[:card_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'ibank'
payment = InternetBankingPayment.new(params[:internet_banking_payment])
payment.amount = #income_voucher.amount
else
payment = CashPayment.new
payment.amount = #income_voucher.amount
end
payment_mode = PaymentMode.new
payment_mode.transactionable = payment
#income_voucher.payment_mode = payment_mode
respond_to do |format|
if #income_voucher.save
format.html { redirect_to(#income_voucher, :notice => 'Income voucher was successfully created.') }
format.xml { render :xml => #income_voucher, :status => :created, :location => #income_voucher }
else
format.html { render :action => "new" }
format.xml { render :xml => #income_voucher.errors, :status => :unprocessable_entity }
end
end
def income_voucher_partial
#payment_mode = PaymentMode.new(params[:payment_mode])
end
end
i can see my view form but when select a radio button nothing is rende. Any help would be appreciated
First of all: choose the method - or you using remote form, or ajax submit. If your want that user choose radio button AND click submit to render use in .html.erb:
form_for(#income_voucher, :remote => true)
remove javascript ajax and change param name in .js.erb to :transaction_type
If you want that user choosse radio button and immidiately render move javascript ajax to radio button change event handler like this
$(your_element).change(function(){
$.ajax(){
url : "/income_vouchers/income_voucher_partial",
data: {
type: $('form input[type=radio]:checked').val()
}
}
});
and remove params setting from directly url - set params in 'data:'
in my js.erb file i did this
$(".gradeU").remove();
$("#abcd").after(
'<%= escape_javascript render :partial => params[:payment] unless params[:payment] == 'cash' %>'
);
and in my script :
$(document).ready(function(){
$("#check").click(function(){
var payment = $('form input[type= radio]:checked').val()
console.debug(payment);
$.ajax({
type: 'GET',
url : "/income_vouchers/income_voucher_partial?payment="+payment,
});
});
});
and i did not render same code in form, thanks
I want to add buttons on my article so that I can know the number of times its clicked and update counter on the database, I am using mongoid ,my model is:
class Article
include Mongoid::Document
include Mongoid::Timestamps
field :title, :type => String
field :content, :type => String
field :likes, :type => Integer ,:default => 0
field :dislikes, :type =>Integer, :default => 0
field :spam, :type => Integer, :default => 0
end
My articles show controller is:
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #article }
end
end
My View for show is:
<p id="notice"><%= notice %></p>
<p>
<b>Title:</b>
<%= #article.title %>
</p>
<p>
<b>Content:</b>
<%= raw #article.content %>
</p>
Likes : <%= #article.likes %> <br/>
Dislikes : <%= #article.dislikes %><br/>
Spams : <%= #article.spam %><br/>
<%= link_to 'Edit', edit_article_path(#article) %> |
<%= link_to 'Back', articles_path %>
I find anything about it in internet.
How can I achieve it?
The easiest thing to do would be add a click_count integer attribute to your Article model and then increment this in your controller code:
def show
#article = Article.find(params[:id])
#article.increment! :click_count
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #article }
end
end
i got it done, phew!
I added the following form in my show.html.erb:
<%=form_for(#article,:action=>"update") do |f| %>
<%= submit_tag "Like", :name=>"like"%>
<%= submit_tag "Dislike",:name=>"dislike"%>
<%= submit_tag "Spam",:name=>"spam" %>
<%end%>
and wrote the following update controller:
def update
#article=Article.find(params[:id])
if params[:like]
#article.likes=#article.likes+1
elsif params[:dislike]
#article.dislikes=#article.dislikes+1
elsif params[:spam]
#article.spams=#article.spams+1
end
respond_to do |format|
if #article.update_attributes(params[:article])
format.html {redirect_to #article, :notice => "Article Updated"}
else
format.html {render :action=>"edit", :notice=> "Unable to update Article , sorry! :("}
end
end
end
It worked like a charm.
Im a rails noob, so bear with me.
I have the following in new.html.erb:
<h1>New page</h1>
<%= render 'pages/form' %>
<% if #page != 1 %>
<%= button_to 'New Page', pages_path %>
<%= button_to 'Done!', :action=> 'generate' %>
<% end %>
my controller looks like this
def generate
#presentation = current_presentation
respond_to do |format|
format.json { render json: #presentation.pages}
format.html {render :text => "html"}
end
end
I want the response to be JSON, but the code goes to format.html.
How do I instruct the button_to that my requested response is JSON?
Not sure if just one of them or both, but try :remote => true and data-type:
<%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %>
Using a path helper to build the path worked for me. eg.
<%= button_to "Create Widgit", widgits_path(format: 'json'), remote: true %>
I am trying to filter Client Comments by using a select and rendering it in a partial. Right now the partial loads #client.comments. I have a Category model with a Categorizations join. This all works, just need to know how to get the select to call the filter action and load the partial with ajax. Thanks for you help.
Categories controller:
def filter_category
#categories = Category.all
respond_to do |format|
format.js # filter.rjs
end
end
filter.js.erb:
page.replace_html 'client-note-inner',
:partial => 'comments',
:locals => { :com => Category.first.comments }
show.html.erb (clients)
<% form_tag(filter_category_path(:id), :method => :put, :class => 'categories', :remote => true, :controller => 'categoires', :action => 'filter') do %>
<label>Categories</label>
<%= select_tag(:category, options_for_select(Category.all.map {|category| [category.name, category.id]}, #category_id)) %>
<% end %>
<div class="client-note-inner">
<%= render :partial => 'comments', :locals => { :com => #comments } %>
</div><!--end client-note-inner-->
Hope that makes sense.
Cheers.
It's straightforward with a simple onchange
<%= select_tag(:category, options_for_select(Category.all.map {|category| [category.name, category.id]}, #category_id), onchange => 'form.submit()') %>