I want to send the count value,for count the post i am using thumbs up gem in ROR.
Now i want to send the count in json,the vote as post action in def show
def index
#posts = Post.all
respond_with(#posts) do |format|
format.json { render json: #post_names = {:post => #posts.as_json(:only=> [:content, :title]) } }
end
end
I want to send the count value using json,because i want to show that count value in my client side.
You can send vote count by this way. I assume something like this can work..
def index
#posts = Post.all
respond_with(#posts) do |format|
format.json { render :json => #post_names = {:post => #posts.map {|t| {:title => t.title, :content => t.content, :count => t.votes_for }} } }
end
end
Since you're working on the controller, you might find it helpful to look at the render section of the Rails documentation.
Related
So I'm trying to let the user sort an array of recipes from a link in my view:
<%= link_to "Score", recipes_sort_path, :order => 'score' %>
I send the parameter "score" to my controller method "sort", which looks like this:
def sort
if (params[:order] == 'score')
#recipes.sort_by(&:score)
end
respond_to do |format|
format.html { redirect_to recipes_path }
format.json { render json: #recipe }
end
end
It redirects to the following index method:
def index
# If recipes already present, skip following
if (!#recipes)
if (params[:search] || params[:tag])
#recipes = Recipe.search(params[:search], params[:tag])
else
#recipes = Recipe.all
end
end
respond_to do |format|
format.html
format.json { render json: #recipe }
end
end
The idea was to be redirected to the index view with the sorted list and just render the view.
I get no errors, but when I click the link, the page reloads but nothing happens.
The Recipe class looks like this:
class Recipe < ActiveRecord::Base
attr_accessible :instructions, :name, :slug, :score, :upvotes, :downvotes, :comments, :image
has_and_belongs_to_many :ingredients
has_and_belongs_to_many :tags
has_many :comments
belongs_to :user
delegate :name, :to => :user, :prefix => :user, :allow_nil => true
mount_uploader :image, ImageUploader
validates :name, :presence => true
def score
score = (self.upvotes - self.downvotes)
end
end
What am I doing wrong here?
There's a third option (the first 2 is from ckruse's answer). You can render the index template from the sort action
def sort
if (params[:order] == 'score')
#recipes.sort_by!(&:score)
end
respond_to do |format|
format.html { render :index }
format.json { render json: #recipe }
end
end
This will use the index template while using #recipes in the sort action. You also save one request because you're not redirecting.
One more thing I'd like to comment on is the link. It should be
<%= link_to "Score", recipes_sort_path(:order => 'score') %>
UPDATE: fetching #recipes. As much as possible, I want sql to do the sorting so that's what I'm going to do here.
def sort
#recipes = Recipe
if params[:order] == 'score'
#recipes = #recipes.order('upvotes - downvotes')
end
respond_to do |format|
format.html { render :index }
format.json { render json: #recipe }
end
end
First of all: sort_by is not „destructive,” it returns a new array. You may want to use sort_by! or save the return value of sort_by into #recipes.
Second: you do not render anything in your sort action at all. If you posted all code, even #recipes is empty. You can do two things:
Retreive the data in your sort method as you did in your index method and then call render :index
Sort in your index method and do not use a sort method at all. You can route multiple URIs to the same action.
my current json output is "id":3,"name":"test", and I need the 3 to be "3".
How would I go about doing this in rails?
def search
#tags = Tag.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => #tags.to_json(:only => [:id, :name]) }
end
end
Sergio's solution will work. However, if you're doing this in more than one place, I would suggest overriding Rails' built in function as_json.
In your Tag model:
def as_json(options={})
options[:id] = #id.to_s
super(options)
end
Your controller method will remain unchanged. This is untested, but should work.
Something like this:
format.json do
tags = #tags.to_json(:only => [:id, :name])
render :json => tags.map{|t| t['id'] = t['id'].to_s; t}
end
This was the only solution that worked for me:
def search
#tags = Tag.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => #tags.map {|t| {:id => t.id.to_s, :name => t.name }} }
end
end
This should have been a relatively simple one but I must be making a mistake with my routes or something. I want to return an active record as json based on an id. So heres what I have and in my eyes it should have worked.
The route:
match '/repository/infoid/(.:id)(.:format)' =>'repo#infoID', :via =>:get
The def within the controller
def infoID
puts (params[:id])
#specificObject = myObject.find_by_id(params[:id])
respond_to do |format|
format.xml{
render :xml =>
{
:returnedObject => #specificObject
}
}
end
end
Why is it that when I go to my address of http://127.0.0.1:3008/repository/infoid/1.xml
I get no route found for /infoid/1.xml
get '/repository/infoid/:id' => 'repo#infoID'
little refacrtoring for controller
def infoID
#specificObject = MyObject.find(params[:id])
respond_to do |format|
format.html{}
format.xml{
render :xml => #specificObject
}
end
end
I recently changed the pagination with will_paginate in my Rails (2.3.4) app to use Ajax for the pagination and records per page. The pagination was done using the method described here: http://github.com/mislav/will_paginate/wiki/Ajax-pagination
I'm using this code in my view:
Records per page: <%= select_tag :per_page, options_for_select([4,8,24,100,500], #per_page.to_i), :onchange => remote_function(:url => users_path, :method => :get, :with => "'per_page=' + this.getValue()") %>
This works fine if I'm not viewing search results. But if I do a search and them attempt to change the records-per-page, my search results are lost and all records are returned. I'm pretty sure this is due to the url I'm calling in my remote_function, but I don't know how to fix it.
This is the code in my controller:
def index
#search = User.search(params[:search])
#search.order||="ascend_by_last_name"
if #search.count > 0
#users = #search.paginate(:page => params[:page], :per_page => users_per_page )
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
format.csv { send_data #users.to_csv }
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace 'results', :partial => 'userview'
end
}
end
else
flash[:notice] = "Sorry, your search didn't return any results."
redirect_to users_path
end
end
Any help would be appreciated! Thanks.
You can append the per_page param to the end of the current query string.
:with => "'#{request.query_string}&per_page=' + this.getValue()"
This assumes there is a current query string, which could cause issue.
I am new to rails so could use some help here. I have followed several tutorials to create a blog with comments and even some of the AJAX bells and whistles and I am stuck on something that I hope is easy. The default display for both blogs and comments is to list the oldest first. How do I reverse that to show the most recent entries and the most recent comments at the top. Don't really know if this is a function of the controller or model. I have done some customization so here is the code for the controller .rb files if it helps.
COMMENTS CONTROLLER
class CommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create!(params[:comment])
respond_to do |format|
format.html { redirect_to #post}
format.js
end
end
end
POSTS CONTROLLER
class PostsController < ApplicationController
before_filter :authenticate, :except => [:index, :show]
# GET /posts
# GET /posts.xml
def index
#posts = Post.all(:include => :comments)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #posts }
format.json { render :json => #posts }
format.atom
end
end
# GET /posts/1
# GET /posts/1.xml
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #post }
end
end
# GET /posts/new
# GET /posts/new.xml
def new
#post = Post.new
respond_to do |format|
format.html { redirect_to #post}
format.js
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.xml
def create
#post = Post.new(params[:post])
respond_to do |format|
if #post.save
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(#post) }
format.xml { render :xml => #post, :status => :created, :location => #post }
else
format.html { render :action => "new" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.xml
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
flash[:notice] = 'Post was successfully updated.'
format.html { redirect_to(#post) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #post.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.xml
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to(posts_url) }
format.xml { head :ok }
end
end
private
def authenticate
authenticate_or_request_with_http_basic do |name, password|
name == "admin" && password == "secret"
end
end
end
As jtbandes pointed out, to reverse the posts in the index, you'd change the line in your index action to read:
#posts = Post.all(:include => :comments, :order => "created_at DESC")
In order to reverse the listing of your comments, there are two possibilities.
Option 1: In your post model you can declare your relationship like so:
class Post < ActiveRecord::Base
has_many :comments, :order => "created_at DESC"
end
Option 2: In your index view, simply reverse the array of each post's comments before displaying them:
<% #posts.each do |post| %>
<%= render :partial => post %>
<%= render :partial => post.comments.reverse %>
<% end %>
The options have different use cases. In option 1, you're saying that throughout your entire application, any time you refer to the comments on a post, those comments should be retrieved from the database in the specified order. You're sort of saying that this is an intrinsic property of comments in your application - posts have many comments, which are by default ordered newest first.
In option 2, you're simply reversing the comments in the index page before they're rendered. They were still retrieved in the original order (oldest first) from the database, and they'll still appear in that order anywhere else you access the comments of a post in your application.
If you're looking for a more generic way to reverse the order of the .each method, Rails has the .reverse_each method. Like so:
<% #posts.reverse_each do |post| %>
<%= render :partial => post %>
<%= render :partial => post.comments.reverse %>
<% end %>
#posts = Post.find(:all, :include => :comments, :order => "published_at DESC")
It looks like you can reverse the order using find: something like Post.find(:all, :order => "created_at DESC"). The same should apply to comments.
.reverse_each method bumping with will_paginate
here is the solution
#posts = Post.all.paginate(:order => "created_at DESC",:page => params[:page],:per_page => 5)
try use: reverse_order
Client.where("orders_count > 10").order(:name).reverse_order
this will execute the SQL:
SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
If no ordering clause is specified in the query, the reverse_order orders by the primary key in reverse order.
Client.where("orders_count > 10").reverse_order
which will execute:
SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
http://edgeguides.rubyonrails.org/active_record_querying.html#reorder