Rails routing: Giving default values for path helpers
I think you will want to do something like this:
class ApplicationController < ActionController::Base
def url_options
{ :current_brand => @current_brand }.merge(super)
end
end
This method is called automatically every time url is constructed and it's result is merged into the parameters.
For more info on this, look at: default_url_options and rails 3
Using defaults values for scoped route in Rails 4 always overrides default_url_options
Setting the default region that way doesn't appear to work; however, according to the Guides, it should:
http://guides.rubyonrails.org/routing.html#defining-defaults
Why not drop the default if nil
is an acceptable value?
config/routes.rb
scope "(:region)", region: /en|se|dk|no|ww/ do
resources :blogs
end
As a workaround, you could set a default region like so:
app/controllers/application_controller.rb
def default_url_options(options={})
{ region: params[:region] || "ww" }
end
Update:
Without a default region:
config/routes.rb
scope "(:region)", region: /en|se|dk|no/ do
resources :blogs do
resources :posts
end
end
app/controllers/application_controller.rb
def default_url_options(options={})
{ region: params[:region] }
end
In your view:
<% @blog.posts.each do |post|
<%= link_to post.title, blog_post_path(@blog, post) %>
<% end %>
URL when no region is specified:
/blogs/1/posts/1
URL when en
region is specified:
/en/blogs/1/posts/1
Update #2:
Ok, I was able to reproduce your failing test. This is caused by a Rails bug and it's the same one you mentioned in your question. You can read more about the issue and some workarounds here:
https://github.com/rspec/rspec-rails/issues/255
To get your tests passing, one approach is to initialize the region
option in default_url_options
using a before(:all)
block. Try adding the following to your RSpec configuration:
spec/rails_helper.rb
RSpec.configure do |config|
config.before(:each) do
default_url_options[:region] = nil
end
end
You'll probably want to restrict that block to feature
and controller
group types.
Hope that helps.
Rails: routing and path helpers
You may have plurals turned off, but this only affects the table names in the database, not how Rails handles routes.
Because the search
route belongs to a collection, not a member, it acts on multiple model objects. Therefore, the route should be search_qtl_tables_path
, note plural tables.
qtl_table
is a model, and you want to search a collection of them, so it make senses that the route reads like "search multiple records".
edit: My main concern is that your rake routes
shouldn't be showing those qtl_table routes twice. Are you repeating yourself somewhere in routes.rb
?
OK, so you've deleted the extra routes. Now, this should work...
<%= form_tag search_qtl_table_index_path, :method => 'get' do %>
default_url_options and rails 3
To set url options for current request use something like this in your controller:
class ApplicationController < ActionController::Base
def url_options
{ :profile => current_profile }.merge(super)
end
end
Now, :profile => current_profile will be automerge to path/url parameters.
Example routing:
scope ":profile" do
resources :comments
end
Just write:
comments_path
and if current_profile has set to_param to 'lucas':
/lucas/comments
helper path generated by Rails based on a custom REST method fails
As posted in the description, here is the "usage".
# GET /reso
def show
...
@reset_path = "foo_reso"
...
end # show
However, all the above is doing is just setting the @reset_path
instance variable into a literal string `"foo_reso" (which coincidentally matches the old route)
What the poster really wants is :
@reset_path = foo_reso_path
which will generate the right path /reso/foo
into the instance variable @reset_path
Sidenote: The poster has done all the right things here to debug route problems. Most of the time, you can trust rake routes
. Checking that one can access the route directly is good, and so is checking the usage of the route helper is correct too is crucial
Rails routes with :name instead of :id url parameters
params
The bottom line is you're looking at the wrong solution - the params
hash keys are rather irrelevant, you need to be able to use the data contained inside them more effectively.
Your routes will be constructed as:
#config/routes.rb
resources :controller #-> domain.com/controller/:id
This means if you request this route: domain.com/controller/your_resource
, the params[:id]
hash value will be your_resource
(doesn't matter if it's called params[:name]
or params[:id]
)
--
friendly_id
The reason you have several answers recommending friendly_id
is because this overrides the find
method of ActiveRecord
, allowing you to use a slug
in your query:
#app/models/model.rb
Class Model < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
end
This allows you to do this:
#app/controllers/your_controller.rb
def show
@model = Model.find params[:id] #-> this can be the "name" of your record, or "id"
end
url_for and route defaults in Rails 3
'resources' line should already provide you with the routes you probably want so you can just remove first 'match' line.
Note that you can also use 'teams_path', 'team_path("cleveland-indians")' instead of 'url_for'.
What does default: { action: 'method' } do in rails routes?
TL;DR
if we would have
resources :assesments, defaults: { format: 'jpg' }, default: { format: 'xml'}
and we would visit localhost/assessments
than params
hash would look like:
{
"format"=>"jpg", # FROM defaults: {}
"default"=> { "format"=>"xml" }, # FROM default: {}
"controller"=>"assesments", WE CAN NOT CHANGE IT. COMES FROM RAILS
"action"=>"index" # WE CAN NOT CHANGE IT. COMES FROM RAILS
}
--- more
defaults: { anything_key: 'any_value' }
will add hash content to params
hash accessible inside controller (however you can not override values provided by controller - that is: :action
and :controller
).
Adding defaults: { action: :anything }
will not have any effect but adding defaults: { format: 'jpg' }
will add { format: 'jpg' }
to params
hash inside all controllers wrapped by routing scope.
Adding default: { some_key: 'value' }
will add this hash (default: { some_key: 'value' }
) to every params hash inside controllers wrapped by routing scope.
Related Topics
How to Download a Ruby Gem Without Installing It Automatically
Normal Variables VS Instance Variable in Ruby, Whats the Difference
How to Assert That No Route Matches in a Rails Integration Test
How to Read Post Data in Rack Request
Distributing Rails Applications as Native Applications
Thin Doesn't Respond to Sigint or Sigterm
How to Ensure a Rake Task Only Running a Process at a Time
Made a Mistake Installing Rvm with Sudo. How to Reverse
Calling a Class Method Within a Class
Why Does Psych Yaml Interpreter Add Line Breaks Around 80 Characters
How to Extend a Class from an Initializer and Have It Reload in Development Environment
Change The Ruby Process Name in Top
What Are Some Examples of Using Nokogiri
How to Pass Named Arguments to a Rake Task
Result.Credit_Card_Verification Is Returning Nil Even on Error in Braintree
Rails Server Does Not Start -> Could Not Find a JavaScript Runtime