Ruby/Rails 3.1: Given a URL string, remove path
With URI::join:
require 'uri'
url = "http://foo.example.com:8080/whatsit/foo.bar?x=y"
baseurl = URI.join(url, "/").to_s
#=> "http://foo.example.com:8080/"
Remove controller_name from URL in Rails 3 and use custom string instead of id
To define that route, try adding the following to your routes.rb:
match '/:id' => 'your_controller#your_action'
This will pretty much match everything to the id of your model. And that's not very nice... You don't want to route youe_host/pages to the pages controller, with an id equal to 'pages'... To prevent that from happening, make sure to put that line on the end of the routes.rb file. The router uses the first route that matches the path received, so putting that line on the end of it will make sure that it will only match your route after it ran out of other meaningful options.A better practice would be to pass regexp constraints to the router, so that it will only match ids with a specific format, like that:
match '/:id' => 'your_controller#your_action', :constraints => { :id => /your_regexp/ }
Refer to the guides if you have doubts about the rails rounting system. It is pretty well written and covers lots of important things. Rails rounting - Official Guides
edit: to create a named route, one that you can call in your controllers and override the normal routes that you are probably creating with resource
, you have to provide the :as =>
parameter in your routes.rb
match '/:id' => 'your_controller#your_action', :as => some_name
Then you'll be able to call it in your controller/views like this:link_to some_name_path(@my_string_id)
Hope this helps. And take a time to read the guides, it has really lots of useful info, including more details about creating named routes. How to call a certain path in delete method Rails
You can pass arguments to the path helper:
someother_path(first_argument: 'whatever')
Also, if you want the full path of the link (including domain host + port), use this:someother_url(first_argument: 'whatever')
The last option is to write the path as a string, for example:link_to 'Destroy', "/posts/#{post.id}/destroy" # etc.
But this last option should not be used as it is complicated to maintain. How to get URL of a delete method off resource?
I don't think this is the right place to pass the {method: :delete}
params. That would go in your helper, like link_to
.
link_to('Yum', potato_url(obj), data: { method: :delete })
If you inspect the output of that you'll see something like:<a data-method="delete" href="/potatos/1" rel="nofollow">Yum</a>
Similarly if you're using a form_for
or form_tag
. That's where you specify the http method, not the named path or url. Redirect all break url to a specific method - In Ruby on Rails
duplicate question
Rails catch-all route
all routes that are not catched prior to this one will be dispatched toput
match '*path' => 'your_controller#your_action' at the end of the
routes.rb file. This is important, since the routes are stepped
through top down.See also http://guides.rubyonrails.org/routing.html -> 3.10
your_controller#your_action
Converting to valid urls which can be opened by open-uri
uri = URI("www.google.com")
if uri.instance_of?(URI::Generic)
uri = URI::HTTP.build({:host => uri.to_s})
end
content_file = open(uri)
There are other ways as well see ref: http://www.ruby-doc.org/stdlib-2.0.0/libdoc/uri/rdoc/URI/HTTP.html Deleting an entire entry from your databse
You are missing a comma between 'Delete' recipes
in the arguments list:
<%= link_to 'Delete', recipes, method: :delete %>
Which solves the syntax error. However placing an <a>
inside a <button>
tag is invalid HTML. Either just style a regularPermitted content
Phrasing content but there must be no Interactive content
- MDN Web Docs: The Button element
<a>
with CSS to look like a button or create a discrete form with button_to
:<%= button_to 'Delete', recipes, method: :delete %>
Since you seem to be just flailing around you can get an example of the how to actually code this by running the scaffold generator. $ rails g scaffold recipe title:string
Which generates:# config/routes.rb
Rails.application.routes.draw do
resources :recipes
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
# app/controllers/recipes_controller.rb
class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
# GET /recipes
# GET /recipes.json
def index
@recipes = Recipe.all
end
# ...
# DELETE /recipes/1
# DELETE /recipes/1.json
def destroy
@recipe.destroy
respond_to do |format|
format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe
@recipe = Recipe.find(params[:id])
end
# ...
end
# app/views/recipes/index.html.erb
<table>
<thead>
<tr>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @recipes.each do |recipe| %>
<tr>
<td><%= link_to 'Show', recipe %></td>
<td><%= link_to 'Edit', edit_recipe_path(recipe) %></td>
<td><%= link_to 'Destroy', recipe, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
Note that in Rails proper pluralization is very important as it ties in with the whole convention over configuration approach. Parse a URL and remove end portion
What kind of output you have after processing your code?
Edited
Your problem is that you convert elementto_i
and it is 0
. But you want to compare index
of element, but can normally get index
of element in that situation using Array#index method.Correct approach:
@request_path.drop_while { |i| @request_path.index(i) >= @comment_index }
You can parse path
without drop_while
.My solution:
def resource_details(path)
resource_array = path.downcase.split("/").reject!(&:empty?)
key = resource_array.index("comments")
return key.present? ? (resource_array - resource_array[key..key + 1]).last(2) : resource_array.last(2)
end
It will cut out ["comments"]
or ["comments","2"]
for your path.Invoke that method:
1.9.3p0 :051 > resource_details("/locations/1/buildings/3/comments")
=> ["buildings", "3"]
1.9.3p0 :052 > resource_details("/locations/1/comments/2")
=> ["locations", "1"]
How to parse url to get base url? -- Rails 3.1
Try to use 'uri' library:
require 'uri'
address = 'http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007'
uri = URI.parse(address)
puts "#{uri.scheme}://#{uri.host}" # => http://www.1800contacts.com
How can I remove the question mark ? in JS and CSS path to files in Ruby on Rails 2.3.5
This is a asset cache breaking mechanism in Rails. You can disable it in your environment.rb
or the environment specific file with
ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
See https://github.com/rails/rails/blob/2-3-stable/actionpack/lib/action_view/helpers/asset_tag_helper.rb#L517 as well.
Related Topics
Need Help on Reading Emails with "Mail" Gem in Ruby
How to Resize Image Only If Width Exceeds with Graphics/Image Magick
Browsing Ruby Code a La Smalltalk
How to Open File in Default Application. Ruby
Why Does Ruby Parallel Assignment with Array of Strings Returns String
How to Override a Variable in a Ruby Subclass Without Affecting The Superclass
Unit Testing Code Which Gets Current Time
If I Have a Stripe Token from a Charge, How to Get Its Charge Id
Ruby Datamapper Table Inheritance with Associations
Functional Testing of a Restful Post in Ruby on Rails
How to Get Meta Keywords Using Nokogiri
How to Get All Message History from Hipchat for a Room via The API
Combining Ruby on Rails and Backbone
What's The Best Way to Test Delayed_Job Chains with Rspec
Rails Routes: Nested, Member, Collection, Namespace, Scope and Customizable
How to Use Variable Arguments with Ruby's Optionparser