If I enter the following URL in a browser, I get a list of client records:
http://localhost:5000/clients.json
Now, I would like to be able the select certain clients via the URL. Is something like this possible:
http://localhost:5000/clients.json?locname=ys
This is my clients_controller.rb for index:
def index
#clients = Client.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end
THANKS!
This should do the job:
def index
#clients = Client.scoped
#clients = #clients.where(:locname => params[:locname]) if params[:locname].present?
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end
Related
I am using Rails 4 with the Impressionist gem to get view count of my Articles.
On my index page I have a link labeled "Most Popular"
I also have access to a method that will order articles by the view count:
#articles = Article.order('impressions_count ASC')
What is the best way to order the index by impression_count when a user clicks the "most popular button?" I am having trouble finding documentation on this.
Here is my articles_controller.rb
class ArticlesController < ApplicationController
load_and_authorize_resource
before_action :set_article, only: [:show, :edit, :update, :destroy]
def index
if params[:q].present?
#articles = Article.search(params[:q], misspellings: {edit_distance: 1}, page: params[:page], per_page: 12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
else
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
if #articles.blank?
return redirect_to request_path
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
get_query
end
def autocomplete
#articles = Article.search params[:term], autocomplete: true
render json: #articles
end
def search
#articles = Article.search params[:q], suggest: true, page: params[:page], per_page: 5
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
render 'index'
end
def show
impressionist(#article, nil, { unique: [:session_hash] })
#skip_error = true
#subarticles = #article.subarticles.approved.order(:cached_votes_score => :desc)
if request.path != article_path(#article)
redirect_to #article, status: :moved_permanently
else
respond_to do |format|
format.html # show.html.erb
format.json { render json: #article }
end
end
end
def new
end
def edit
end
def create
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: #article }
else
format.html { render :new }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #article.update(article_params)
format.html { redirect_to #article, notice: 'Article was successfully updated.' }
format.json { render :show, status: :ok, location: #article }
else
format.html { render :edit }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
def destroy
#article.destroy
respond_to do |format|
format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
#article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:title, :specific, :category, :aka, :image1, :image2, :video1, :video2)
end
def get_query
#userquery = params[:q]
end
end
The first else clause in your index is this:
else
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
That is why you are getting them sorted by impressions_count. Just get rid of it to return them sorted by most recent.
else
#articles = Article.order(created_at: :desc).page(params[:page]).per(12)
You then need to set your "most popular" link to return the #articles variable sorted by impressions_count as you did in your old code.
You will need to make your action in the controller to return the results you want, something like:
Add a variable to your whitelist:
def article_params
params.require(:article).permit(:title, :specific, :category, :aka, :image1, :image2, :video1, :video2, :imp_sort)
end
Then in your index action you can add it in:
def index
if params[:q].present?
#articles = Article.search(params[:q], misspellings: {edit_distance: 1}, page: params[:page], per_page: 12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
else
if article_params[:imp_sort]
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
else
#articles = Article.order(created_at: :desc).page(params[:page]).per(12)
end
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
if #articles.blank?
return redirect_to request_path
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
get_query
end
in your index.html.erb you will need to have your link do something like:
<%= link_to "Sort by Impressions", articles_path(:imp_sort => true) %>
I want to grab content from a website, that I input into a submit form, and store that info as a json I can save to my db. I am trying to use HTTParty, but I'm not quite sure how to implement it to grab the data. Here is what I have so far.
controller
class UrlsController < ApplicationController
before_action :set_url, only: [:show, :edit, :update, :destroy]
#require "addressable/uri"
#Addressable::URI.parse(url)
# GET /urls
# GET /urls.json
def index
#urls = Url.all
end
# GET /urls/1
# GET /urls/1.json
def show
end
# GET /urls/new
def new
#url = Url.new
end
# GET /urls/1/edit
def edit
end
def uri?(string)
uri = URI.parse(string)
%w( http https ).include?(uri.scheme)
rescue URI::BadURIError
false
rescue URI::InvalidURIError
false
end
# POST /urls
# POST /urls.json
def create
#url = Url.new(url_params)
#app_url = params[:url]
respond_to do |format|
if #url.save
format.html { redirect_to #url, notice: 'Url was successfully created.' }
format.json { render action: 'show', status: :created, location: #url }
wordcount
else
format.html { render action: 'new' }
format.json { render json: #url.errors, status: :unprocessable_entity }
end
end
end
def wordcount
# Choose the URL to visit
#app_url = #url
#words = HTTParty.get(#app_url)
# Trick to pretty print headers
#wordcount = Hash[*#words]
end
# PATCH/PUT /urls/1
# PATCH/PUT /urls/1.json
def update
respond_to do |format|
if #url.update(url_params)
format.html { redirect_to #url, notice: 'Url was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #url.errors, status: :unprocessable_entity }
end
end
end
# DELETE /urls/1
# DELETE /urls/1.json
def destroy
#url.destroy
respond_to do |format|
format.html { redirect_to urls_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_url
#url = Url.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def url_params
params.require(:url).permit(:url)
end
end
That is my controller.rb. I am getting a 'bad argument (expected URI object or URI string)' from the line #words = HTTParty.get(#app_url) I need to change what url is put into the form to a valid URL, grab the content I want from that URL, and save that information.
Try something like this:
response = HTTParty.get('https://google.com')
puts response.body, response.code, response.message, response.headers.inspect
To answer your question you can implement the following method, make a new class or put it in a helper.
Might need to include HTTParty
def url_getter(url)
HTTParty.get(url)
end
and call it:
url_getter(#app_url)
I have a /tags.json where i want to render a list of players and teams, using the following which i have put in both players and teams model.
def token
"#{id}_#{self.class.name}"
end
Tags controller
def index
#players = Player.all
#teams = Team.all
#tags = #teams + #players
respond_to do |format|
format.json { render json: #tags}
end
end
But how can i create a list in my tags controller, so i can get something like this
[
{"name":"Bob","token":"1_Player"},
{"name":"Yankees","token":"1_Team"}
]
How can i do this?
Edit
format.json { render json: #tags.as_json(only: [:name])}
renders
[
{"name":"Bob"},
{"name":"Yankees"}
]
But how could i get token?
Try something like this:
#tags = []
Team.all.each do |team|
#tags.push({name: team.name, tag: team.token})
end
Player.all.each do |player|
#tags.push({name: player.name, tag: player.token})
end
respond_to do |format|
format.json { render json: #tags}
end
In my Rails app, I have a comments scaffold which lets users comment on a movie.
I am faced with two problems.
The first problem is that anyone can create a comment, even if they are not signed in, how would I assign a comment to a user, so if there is a current_user, they can create a comment and I would be able to assign the user to the comment so <%= comment.user.first_name %>, and if they are not signed in, they cant create a comment. How would i do this? ( I am using devise )
The second problem is that when I create a comment, it takes me to this path (where 12 is :movie_id)
localhost:3000/movies/12/comments/new
This is fine but when i am creating the comment, I have to specify the movie_id (12), how this be done automatically, so rails sees that the movie_id for the comment is 12.
My Comments Controller, incase needed
class CommentsController < ApplicationController
# GET /comments
# GET /comments.json
before_filter :load_movie
def index
#comments = #movie.comments.all
#search = Movie.search(params[:q])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #comments }
end
end
# GET /comments/1
# GET /comments/1.json
def show
#comment = Comment.find(params[:id])
#search = Movie.search(params[:q])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #comment }
end
end
# GET /comments/new
# GET /comments/new.json
def new
#comment = Comment.new
#search = Movie.search(params[:q])
respond_to do |format|
format.html # new.html.erb
format.json { render json: #comment }
end
end
# GET /comments/1/edit
def edit
#comment = Comment.find(params[:id])
#search = Movie.search(params[:q])
end
# POST /comments
# POST /comments.json
def create
#comment = Comment.new(params[:comment])
#search = Movie.search(params[:q])
respond_to do |format|
if #comment.save
format.html { redirect_to :back }
format.json { render json: #comment, status: :created, location: #comment }
else
format.html { render action: "new" }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# PUT /comments/1
# PUT /comments/1.json
def update
#comment = Comment.find(params[:id])
#search = Movie.search(params[:q])
respond_to do |format|
if #comment.update_attributes(params[:comment])
format.html { redirect_to (#movie), notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
#comment = Comment.find(params[:id])
#comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
private
def load_movie
#movie = Movie.find_by_id(:movie_id)
end
end
First:
using devise, you can request that a user is signed in by saying at the top of your controller:
before_filter :authenticate_user!, only: [:new,:create]
so if someone not signed in tries to access these actions, they are redirected to the sign in page and after sign in forwarded to the original request.
Second:
As you can see from the routes, 12 is assigned to params[:movie_id]. So in your controllers new action write:
#movie = Movie.find(params[:movie_id])
#comment = #movie.comments.new
#comment.user=current_user
I have a module that returns an array:
module Module1
class Class1
def self.get
num << 1
return num
end
end
end
But when I call it from the controller like this:
def index
#trans = Module1::Class1.get()
respond_to do |format|
format.html # index.html.erb
format.json { render #trans }
end
end
Show me the following error:
'1' is not an ActiveModel-compatible object that returns a valid partial path.
But if I do in json:
def index
respond_to do |format|
format.html # index.html.erb
format.json { render Module1::Class1.get() }
end
end
It returns the right result, what am I doing wrong in the first example?
Try this
format.json { render :json => #trans }