create an 'action' drop down box to decide order of table - ruby-on-rails

I have an index page which has a table in it. I'd like a drop down box that will display various ways to order the table. like this:
'<%= f.select :order_by [service_date, Car_name, etc.]'
I'm not sure what to put in my controller to be able to read the value in the drop box and then submit the new order
#index_controller
def index
#cars = Car.find(:all, :order => 'value of drop down box in here')
#cars_available = Car.where(:available => true, :booked => false)
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #cars}
end
end
any ideas?

It works like any other form parameter:
# GET
def index
#cars = Car.find(:all, :order => params[:car][:order_by])
#cars_available = Car.where(:available => true, :booked => false)
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #cars}
end
end
You should define an instance method order_by in your Car model to return a default value:
def order_by
"your default order_by" #will determine the default selected order_by on a form
end
PS You need this method, or atleast attr_reader :order_by or attr_accessor :order_by, or else you will get an Execption for f.select :order_by

Related

How to send the count value using JSON in ROR

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.

Rails: trouble sorting array from view

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.

passing variables between methods in ROR controller

In my controller I pass date from method create to method index. How can I pass it back from index to create (for new create)?
def index
#date = params[:date].
end
def create
<<<NEED to get #date from index here>>>
#entry = Entry.new(:input => input, :user => current_user, :time => #date)
respond_to do |format|
if #entry.save
format.html { redirect_to(:action => "index", :edit => true) }
end
end
Why do you need to get it from index?
Keep it in a hidden form variable and submit it, etc. You can't get it from index.

Changing number of returned search results with Rails and Ajax

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.

How do I access the ID of a resource already loaded via AJAX if not through the URL params in Rails 3?

If I have a situation where paramters aren't passed explicitly via the URL because there are some ajax elements on the one page, how do I access an ID for an object loaded much earlier....for instance.
User selects client.id=1
User selects, project.id=3
User selects, stages.id=9
But none of those IDs are passed through the URL.
In that example, by the time the user reaches step 3, I would like to access the client.id in the Client controller....how do I do that ?
If it were in the URL, I would just do client = Client.find(params[:id]), but if I do that now, by step 3, what gets returned as the ID parameter is the Stage ID - which is not what I want.
This is what their actions in their respective controllers look like:
Client Step Action
def step
client = Client.find(params[:id])
projects = client.projects
respond_to do |format|
#format.html { redirect_to("/") }
format.html { render :partial => "projects/show", :collection => projects, :as => :project, :layout => false, :status => :ok }
end
end
Project Step Action
def step
project = Project.find(params[:id])
stages = project.stages
respond_to do |format|
format.html { render :partial => "stages/show", :collection => stages, :as => :stage, :layout => false, :status => :ok }
end
end
Stage Step Action
def step
stage = Stage.find(params[:id])
uploads = stage.uploads
respond_to do |format|
format.html { render :partial => "uploads/show", :collection => uploads, :as => :upload, :layout => false, :status => :ok }
end
end
Would tracking the variable in the session object work? For example, in step 1. you do something like session["client_id] = #client.id.

Resources