I want to pass a parameter (for example the param is called company=heise) on a link to, but only if the param really is present.
Lets say:
I visit somesite.com and click a link that would redirect me to mysite.com/?company=heise
On mysite i have a few link_to's and I want them to pass the parameter company=heise when it's present and since it is present now because I entered the site via mysite.com/?company=heise it should do the following:
<%= link_to "This is a link", this_link_path, class: tl(this_link_path) %>
should redirect me to mysite.com/this_link/?company=heise
If company=heise is set I want to display them in the URL and I furthermore want to not display it when it's not set.
Hope I made my question clear enough
Conditionally pass a hash, containing additional params for this_link_path url helper.
<%= link_to "This is a link", this_link_path( ({company: params[:company] } if params[:company]) ), class: tl(this_link_path) %>
To be more concise you can compact the hash.
<%= link_to "This is a link", this_link_path({company: params[:company]}.compact), class: tl(this_link_path) %>
If you know that you'll need it more often, wrap this_link_path call in a custom helper. Hash can contain additional params, including ones with fixed values.
def this_link_with_additional_params_path
this_link_path({company: params[:company], name: 'test'}.compact)
end
Then in view you can use:
<%= link_to "This is a link", this_link_with_additional_params_path, class: tl(this_link_path) %>
The idea here is to create a helper method to manage the params that you want to send to this link conditionally.
# some_helper.rb
def carried_over_params(params = {})
interesting_keys = %i(company)
params.slice(*interesting_keys).compact
end
Afterwards, you should use this in the view
<%= link_to "This is a link", this_link_path(carried_over_params(params).merge(test: 'value')), class: tl(this_link_path) %>
Related
Can i use variable for Rails link_to helper for making different link with variables?
For example,
<%= link_to users, users_path %>
I have link like this,
And i'd like to change this url with variable examples
So i changed url like this,
<%= link_to users, "#{examples}_path" %>
This not worked because of whole string change to url.
How can i change my link_to for use this with different variable for DRY codes?
What you're asking is really just how to perform dynamic method calls. In Ruby you can do it with send (and public_send):
<%= link_to users, send("#{examples}_path") %>
The difference between the two is that send will let you violate encapsulation and call private/protected methods.
You can also do it by calling call on the Method object:
<%= link_to users, method("#{examples}_path".to_sym).call %>
However you most likely don't even need this it in the first place. Just use the polymorphic routing helpers to create links from models:
# a link to show whatever resource happens to be
<%= link_to resource.name, resource %>
<%= link_to "Edit", edit_polymorphic_url(resource) %>
<%= link_to "New", new_polymorphic_url(resource_class) %>
<%= link_to "Frobnobize", polymorphic_url(resource, :frobnobize) %>
# a link to the index
<%= link_to resource_class.model_name.plural, resource_class %>
These all use a set of heuristics to figure out what the corresponing path helper is and then call it dynamically with send.
Or if you want to link to a specific controller or action just use the functionality provided by url_for:
# link to a specific controller action
<%= link_to "Baz", { controller: :foo, action: :bar } %>
# Will use the current controller
<%= link_to "Baz", { action: :bar } %>
I am integrating 2 rails projects using button to link the first project to the second. Now I have this code
<%= form_tag fast_url_for(' ') do %>
<%= button_to AppConfig.app_clockout %>
<% end %>
and my current directory is
/var/www/html/wizTime/wizProject/Source/project_1
but I don't know how can this redirect to the home page of another project. The directory of my second project that I want to integrate is
/var/www/html/project_2
Please give me ideas. Thank you!
If you only want a link_to and your projects will have domains later, you can just create a link like this in rails:
<%= link_to 'sec project', "http://www.rubyonrails.org/" %> which will create an ordinary html link: <a href=""http://www.rubyonrails.org/" ...>
The form usually should not link to another project?!
If after submitting the form you want to redirect the view to another project, than you can use the controller action and redirect after submit.
As the other commenter said - you can just create a link to the other domain. You should not ever rely on your directory-structure - because when you deploy, that directory structure will very likely be subtly different.
So use the domains instead.
You can even put the domains into environment variables so that you can use different domains (eg localhost:3000 vs localhost:3001) on your development machine. you'd use them like this:
<%= link_to 'My App', ENV['MY_APP_DOMAIN'] %>
<%= link_to 'My Other App', ENV['MY_OTHER_APP_DOMAIN'] %>
Then google for how to set environment variables on your local machine to set the values.
If you want them to be buttons... then you don't need to use a form. button_to creates its own form and is used exactly the same way as a link_to eg:
<%= button_to 'My App', ENV['MY_APP_DOMAIN'] %>
<%= button_to 'My Other App', ENV['MY_OTHER_APP_DOMAIN'] %>
However... you really don't need to use a button-to if you are just doing a GET for a URL like this...
(you use buttons when you need to POST data eg POSTing form data to a create action)
You can just pass in a CSS-class and style the link-to to look as though it were a button.
eg using Bootstrap classes:
<%= link_to 'My App', ENV['MY_APP_DOMAIN'], class: 'btn btn-success' %>
<%= link_to 'My Other App', ENV['MY_OTHER_APP_DOMAIN'], class: 'btn btn-danger' %>
OR similar.
I have a PostsHelper, that helps me generate links:
module PostsHelper
def populate_update_link(link1, link2, parameter)
if current_user
public_send(link2, parameter)
else
public_send(link1)
end
end
end
I call it like this:
<%= link_to 'Update', populate_update_link('new_post_path', 'new_post_path', parent_id: #post) %>
What I would like to generate is a link like this though:
<%= link_to "(Update)", "#", class: "togglesidebar" %>
How do I send a class via public_send to the generated link?
According to the rails API, you can setup html options for a given link on the third parameter of link_to (ie http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)
In your case you would need to define another method which return an array of options such as {id: "my_id", class: "my_class_1 my_class_2"} and call this method as the 3rd parameter of link_to.
def generate_html_options(param_1, param_2)
....
body
....
return hash of options
end
Intended to be use like this:
<%= link_to('Update', populate_update_link('new_post_path', 'new_post_path', parent_id: #post), generate_html_options(...)) %>
I want to update a single attribute via a link (click "set as default account", which sets the is_default column to true). I have the following link:
<% #accounts.each do |account| %>
.
.
<%= link_to 'Set as default', account, method: :put %>
... as you can see I'm using "account" object to set the URL. This results in something like "/accounts/7". But, I don't know how to pass the is_default=true param. Should I do something different here? Should I use a *_path? Also I'm guessing I want an address such as "/accounts/7?is_default=true" (or "/accounts/7/setdefault" and configure the controller and routes.rb to handle this?)
How do I pass a param in a string in this case? Also, what is the best practise? I've looked in other questions but can't quite find something specific to this, then again I am a newbie :(
Thanks
You can do it like this, for example
<%= link_to 'Set as default', account_path(account, is_default: true), method: :put %>
Documentation: link_to
Try this
<%= link_to 'Set as default',{:controller => "" ,:action=>"" ,:id => ,:is_default=>true} %>
This question already has answers here:
Add querystring parameters to link_to
(5 answers)
Closed 8 years ago.
I have a logic where I allow sorting on price and relevance. I am doing this by passing parameters to controller. My URL has a parameter - 'sort' which can have a value - 'price_lowest' or 'default'.
The links looks like:
lowest prices |
relevance
problem with the above code is that it "adds" parameters and does not "replace" them. I want to replace the value of &sort= parameter without adding a new value. E.g. I don't want :
../&sort=price_lowest&sort=price_lowest&sort=default
With the current logic - I am getting the above behaviour. Any suggestions ?
In order to preserve the params I did this:
<%= link_to 'Date', params.merge(sort: "end_date") %>
However the url will be ugly.
UPDATE
For Rails 5 use:
<%= link_to 'Date', request.params.merge(sort: "end_date") %>
If you only need one cgi param and want to stay on the same page, this is very simple to achieve:
<%= link_to "lowest prices", :sort => "price_lowest" %>
However, if you have more than one, you need some logic to keep old ones. It'd probably be best extracted to a helper, but essentially you could do something like this to keep the other params..
<%= link_to "lowest prices", :sort => "price_lowest", :other_param => params[:other] %>
Named routes will only really help you here if you need to go to another page.
If a path is not passed to the link_to method, the current params are assumed. In Rails 3.2, this is the most elegant method for adding or modifying parameters in a URL:
<%= link_to 'lowest prices', params.merge(sort: 'end_date') %>
<%= link_to 'relevance', params.merge(sort: 'default') %>
params is a Ruby hash. Using merge will either add a key or replace the value of a key. If you pass nil as the value of a key, it will remove that key/value pair from the hash.
<%= link_to 'relevance', params.merge(sort: nil) %>
Cite:
link_to http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to
url_for
http://apidock.com/rails/v3.2.13/ActionView/Helpers/UrlHelper/url_for
My working solution on Rails 3.1
of course, it's hardcode, and has to be refactored.
item model
def self.get(field,value)
where(field=>value)
end
items controller
#items=Item.all
if params[:enabled]
#items=#items.get(:enabled, params[:enabled])
end
if params[:section]
#items=#items.get(:section_id, params[:section])
end
items helper
def filter_link(text, filters={}, html_options={})
trigger=0
params_to_keep = [:section, :enabled]
params_to_keep.each do |param|
if filters[param].to_s==params[param] && filters[param].to_s!="clear" || filters[param].to_s=="clear"&¶ms[param].nil?
trigger=1
end
if filters[param]=="clear"
filters.delete(param)
else
filters[param]=params[param] if filters[param].nil?
end
end
html_options[:class]= 'current' if trigger==1
link_to text, filters, html_options
end
items index.html.erb
<%= filter_link 'All sections',{:section=>"clear"} %>
<% #sections.each do |section| %>
<%= filter_link section.title, {:section => section} %>
<% end %>
<%= filter_link "All items", {:enabled=>"clear"} %>
<%= filter_link "In stock", :enabled=>true %>
<%= filter_link "Not in stock", :enabled=>false %>
It's not quite the answer to the question that you're asking, but have you thought about using the Sorted gem to handle your sorting logic and view links?