Refresh url if url parameter changes in rails - ruby

I have a url in this format.
/companies/:name?id=company_id
So for example the ABC company, assuming the id is 1,has as url
/companies/ABC?id=1
If someone changes the id parameter value, the company with the new id is correcty loaded and its view is shown but the url keeps showing the previous company name.
For example, having a second company DEF with id 2
/companies/ABC?id=2
Instead of
/companies/DEF?id=2
Is there a way to check that id change and reload the url with the correct company name?
Thank you guys.

The only way to ensure that the :name matches the :id is to compare them, and redirect if the value doesn't match what expected.
For example, you can add a before_action in your controller, or enhance the one where you load the company
before_action :find_company
def find_company
#company = Company.find(params[:id])
# check and redirect
if #company.name != params[:name]
redirect_to(company_path(...))
end
end
Of course, the comparison has to be adjusted depending on how you generate the value for the :name parameter.
Personally, I dislike the approach of having the id as query. I would probably prefer something like:
/companies/:id
and take advantage of the fact that any string with the format \d+-\w+ is translated into an integer in Ruby:
"12-company-name".to_i
=> 12
You can then have URLs like:
/companies/12-company-name
And simply use
Company.find(params[:id].to_i)
Of course, you will still need the before action if you want to redirect in case of name not matching the ID.
before_action :find_company
def find_company
id, name = params[:id].to_s.split("-", 2)
#company = Company.find(id)
# check and redirect
if #company.name != name
redirect_to(company_path(...))
end
end

Related

Checking if a record exists in Sinatra/DataMapper

I currently generate a user's profile page using their serial ID, like so:
get '/users/:id' do
#user = User.get(params[:id])
end
This works great, until a number is entered that doesn't exist in the database.
I'm aware I can change User.get to User.get! to return an ObjectNotFoundError error if the record isn't found, but I'm not sure how I can use this to my aid.
I used to use .exists? when using RoR.
Any suggestions?
Thanks in advance!
Edit: I'm going to leave the question unanswered, as I haven't actually found a solution to what I asked in the title; however, I did manage to solve my own problem by checking to see if the :id entered is higher than the amount of users that exist in the database, like so:
if params[:id].to_i > User.count
"This user does not exist."
else
#users_id = User.get(params[:id])
erb(:'users/id')
end
You already have the correct code:
#user = User.get(params[:id])
If no user exists with the given id, then #get will return nil. Then you can just do a conditional:
#user = User.get params[:id]
if #user
# user exists
else
# no user exists
end
This is a very common pattern in Ruby which takes advantage of the "truthiness" of anything other than false or nil. i.e. you can say if 0 or if [] and the condition will evaluate to true
You can recreate a .exists? method:
class User
def self.exists?(id_or_conditions)
if id_or_conditions.is_a? Integer
!! User.get id_or_conditions
else
!! User.first id_or_conditions
end
end
end
#get is similar to #find in rails, except it doesn't raise an error if the record is not found. #first is similar to #find_by in rails.

Creating a Ruby API

I have been tasked with creating a Ruby API that retrieves youtube URL's. However, I am not sure of the proper way to create an 'API'... I did the following code below as a Sinatra server that serves up JSON, but what exactly would be the definition of an API and would this qualify as one? If this is not an API, how can I make in an API? Thanks in advance.
require 'open-uri'
require 'json'
require 'sinatra'
# get user input
puts "Please enter a search (seperate words by commas):"
search_input = gets.chomp
puts
puts "Performing search on YOUTUBE ... go to '/videos' API endpoint to see the results and use the output"
puts
# define query parameters
api_key = 'my_key_here'
search_url = 'https://www.googleapis.com/youtube/v3/search'
params = {
part: 'snippet',
q: search_input,
type: 'video',
videoCaption: 'closedCaption',
key: api_key
}
# use search_url and query parameters to construct a url, then open and parse the result
uri = URI.parse(search_url)
uri.query = URI.encode_www_form(params)
result = JSON.parse(open(uri).read)
# class to define attributes of each video and format into eventual json
class Video
attr_accessor :title, :description, :url
def initialize
#title = nil
#description = nil
#url = nil
end
def to_hash
{
'title' => #title,
'description' => #description,
'url' => #url
}
end
def to_json
self.to_hash.to_json
end
end
# create an array with top 3 search results
results_array = []
result["items"].take(3).each do |video|
#video = Video.new
#video.title = video["snippet"]["title"]
#video.description = video["snippet"]["description"]
#video.url = video["snippet"]["thumbnails"]["default"]["url"]
results_array << #video.to_json.gsub!(/\"/, '\'')
end
# define the API endpoint
get '/videos' do
results_array.to_json
end
An "API = Application Program Interface" is, simply, something that another program can reliably use to get a job done, without having to busy its little head about exactly how the job is done.
Perhaps the simplest thing to do now, if possible, is to go back to the person who "tasked" you with this task, and to ask him/her, "well, what do you have in mind?" The best API that you can design, in this case, will be the one that is most convenient for the people (who are writing the programs which ...) will actually have to use it. "Don't guess. Ask!"
A very common strategy for an API, in a language like Ruby, is to define a class which represents "this application's connection to this service." Anyone who wants to use the API does so by calling some function which will return a new instance of this class. Thereafter, the program uses this object to issue and handle requests.
The requests, also, are objects. To issue a request, you first ask the API-connection object to give you a new request-object. You then fill-out the request with whatever particulars, then tell the request object to "go!" At some point in the future, and by some appropriate means (such as a callback ...) the request-object informs you that it succeeded or that it failed.
"A whole lot of voodoo-magic might have taken place," between the request object and the connection object which spawned it, but the client does not have to care. And that, most of all, is the objective of any API. "It Just Works.™"
I think they want you to create a third-party library. Imagine you are schizophrenic for a while.
Joe wants to build a Sinatra application to list some YouTube videos, but he is lazy and he does not want to do the dirty work, he just wants to drop something in, give it some credentials, ask for urls and use them, finito.
Joe asks Bob to implement it for him and he gives him his requirements: "Bob, I need YouTube library. I need it to do:"
# Please note that I don't know how YouTube API works, just guessing.
client = YouTube.new(api_key: 'hola')
video_urls = client.videos # => ['https://...', 'https://...', ...]
And Bob says "OK." end spends a day in his interactive console.
So first, you should figure out how you are going to use your not-yet-existing lib, if you can – sometimes you just don't know yet.
Next, build that library based on the requirements, then drop it in your Sinatra app and you're done. Does that help?

Update users table when running create action of different model

Just to show you how I got to this point:
Every user has many profiles. Every profile has type recognized by single table inheritance(amateur, professional, and some other). I need to store current_profile somewhere and somehow.
Professionals Controller
class ProfessionalsController < ApplicationController
def create
#professional = Professional.new(professional_params)
#user = current_user
#professional.user_id = current_user.id
#update_current_profile = User.update(#user, {:current_profile => #professional.id})
if #professional.save
...
else
...
end
end
private
def professional_params
params.require(:professional).permit(:id, :username, :user_id)
end
end
This is meant to update current_profile of user to the newly created professional profile and do some staff then.
When the profile is created current_profile is set(updated) to NULL. If I change :
#update_current_profile = User.update(#user, {:current_profile => #professional.id})
to something different, for example:
#update_current_profile = User.update(#user, {:current_profile => #professional.user_id})
or
#update_current_profile = User.update(#user, {:current_profile => 3})
it stores data in User.current_profile perfectly.
I was trying #professional without an .id too. Why is this doing so?
Another question is. Is this the best way to store current_profile of user? Would you recommend me any better/safer/more efficient solution?
Thanks all of you guys.
#professional is a new, unsaved record and therefore does not have an id yet. Can only update the current_profile once the #professional record was saved.
Just reorder the lines a bit and it should work:
def create
#professional = Professional.new(professional_params)
#user = current_user
#professional.user_id = current_user.id
if #professional.save
#update_current_profile = User.update(#user, {:current_profile => #professional.id})
# ...
else
# ...
end
end
Just another tip: You use many instance variables (the one with the #) in this method. I do not know enough about your code, but I would suggest to look if some of them can be replaced with local variables. Rule of thumb: Only use instance variables in controllers when you want to share that variable with another method or the view.

Changing ID to something more friendly

When creating a record the URL generated to view that record ends with its id
/record/21
I would like to be able to change that to something easier to read, such as my name and reference attributes from the model. I have looked at friendly_id but has trouble implementing a custom method to generate the URL
class Animal < ActiveRecord::Base
extend FriendlyId
friendly_id :name_and_ref
def name_and_ref
"#{name}-#{reference}"
end
end
I ended up getting an error
PG::UndefinedColumn: ERROR: column animals.name_and_ref does not exist LINE 1: SELECT "animals".* FROM "animals" WHERE "animals"."name_an... ^ : SELECT "animals".* FROM "animals" WHERE "animals"."name_and_ref" = 'Clawd-A123456' ORDER BY "animals"."id" ASC LIMIT 1
def show
#animal = Animal.friendly.find(params[:id])
end
I then come across the to_param method which Rails has available, in my model I have
def to_param
"#{self.id}-#{self.name}"
end
which will generate a URL for me of
/19-clawd
This works, but when I do the following it throws an error
def to_param
"#{self.name}-#{self.reference}"
end
My question though is how can I generate the URL to be name and reference without it throwing
Couldn't find Animal with 'id'=Clawd-A123456
If you would like to use your own "friendly id" then you'll need to adjust the find statement in your controller to something like
id = params[:id].split(/-/, 2).first
#animal = Animal.find(id)
Similarly, for the name/reference combination
name, reference = params[:id].split(/-/, 2)
#animal = Animal.find_by(name: name, reference: reference)
The second choice is a little more difficult because you'll have to do some work in the model to guarantee that the name/reference pair is unique.
The easiest way, is to go with friendly_id and simply add the missing database column. Keep in mind that you will need to ensure this new column is unique for every record. It basically acts as primary key.

Rails3 api to retrieve items based on its params using grape

i m working in rails 3
i have a doubt , i have a method to fetch the items based on its tag
like
resources "blogs" do
get '/tag', '/tag/:name' do
authenticate!
tag_name = params[:name].to_s || ""
# query to fetch from items based on its tag associated
end
end
The above one works, now i would like to change the url like
"apipath/blogs?tag=tag1"
instead of what i did before as "apipath/blogs/tag/tag1"
so i have modified the line
get '/tag', '/tag/:name' do
###
end
with
get '?tag', '?tag=:name' do
end
but this not working ...
Please suggest .
To me this can works :
resources "blogs" do
get '/tag' do
authenticate!
tag_name = params[:tag].to_s || ""
# query to fetch from items based on its tag associated
end
end
You don't need define in your route the params pass by ? this is not interpret by router.
You can add conditionals in the route with parenthesis:
get '/tag(/:name)' do
# params[:name] will contain the tag name
end

Resources