How to pass parameter through link_to? - ruby-on-rails

Controller
class FeedEntriesController < ApplicationController
def index
#search = FeedEntry.search(params[:search])
#feed_entries = #search.page(params[:page])
#app_keys = AppKey.all
end
end
My feed_entries/index.html.erb
<%= link_to "Stared", {:controller => "feed_entries", :action => "index", :search => ['is_star = ?', true] }%>
feed_entries table contain is_star:boolean attribute. So, I just want to pass the parameter is_star == true into the params[:search].
But the above code is not working. Please some one help me.

Try
<%= link_to "Stared", {:controller => "feed_entries", :action => "index", :is_star => true } %?
And then you should be able to access in the controller using params[:is_star]

Related

How can I pass params using link_to?

I want to pass a parameter using link_to. (Also I am trying to use Bootstrap tab)
ilban.html.erb
<%= link_to '일반공지', '#home', { 'data-toggle' => 'tab', 'aria-controls'=>'home', 'role'=>'tab', :where => 1 } %>
cpu_controller.rb
#where = params[:where]
This code doesn't get where as an parameter. How can I fix it?
I have not tested it, but it should pass the params that you want.
link_to "Search", searches_path(:where => 1, :when => "Today"), { 'data-toggle' => 'tab', 'aria-controls'=>'home', 'role'=>'tab' }
Controller:
#where = params[:where]
In Rails 5, try this syntax for link_to
link_to 'Show', view_path(:id => view.id), { 'data-toggle' => 'tab', 'aria-controls'=>'home', 'role'=>'tab' }
In the place of view path you can edit with your controller path and pass the valid id that you need to link.
Or, try this syntax also to pass params
<%= link_to "Add car", {:controller => "car", :action => "add_car", :car => car.id }%>
And add in your controller
#car = Car.find(params[:car])

Rails routes option "as", can't edit resource

In my application I have model "Regulation", form for creating regulations looks like this:
- if %W(edit update).include? action_name
= content_for :heading, t('partners.regulations.edit')
- else
= content_for :heading, t('partners.regulations.new')
.row
.col-md-6
= horizontal_simple_form_for [:partners, #regulation] do |f|
= f.error_notification
%ul.nav.nav-pills
%li
= link_to image_tag("flag_pl.png"), '#PL', class: 'regulation_pl'
%li
= link_to image_tag("flag_en.png"), '#EN', class: 'regulation_en'
.polish_regulation
%h1.page-header
= t('partners.regulations.polish')
= f.input :content_pl, :as => :ckeditor, :input_html => { :ckeditor => {:toolbar => 'Pure', width: 750} }, error: false
.english_regulation
%h1.page-header
= t('partners.regulations.english')
= f.input :content_en, :as => :ckeditor, :input_html => { :ckeditor => {:toolbar => 'Basic', width: 750} }, error: false
- if %W(edit update).include? action_name
= f.submit t('actions.save_changes'), class: "btn btn-lg btn-default"
- else
= f.submit t('partners.regulations.save'), class: "btn btn-lg btn-default"
In my routes I have:
namespace :partners do
resources :regulations, as: :rental_company_regulation, except: :show
end
My controller looks like this:
module Partners
class RegulationsController < ApplicationController
include Partners::BaseController
load_and_authorize_resource through: :rental_company, singleton: true
before_action :set_breadcrumbs
before_action :set_regulation, only: :new
def new
if #rental_company_regulation
redirect_to edit_partners_rental_company_regulation_path(#rental_company_regulation)
end
add_breadcrumb t('partners.regulations.new')
end
def create
if #regulation.save
flash[:notice] = t('partners.regulations.created')
redirect_to partners_root_path
else
add_breadcrumb t('partners.regulations.new')
render :new
end
end
def edit
add_breadcrumb t('partners.regulations.edit')
end
def update
if #regulation.update(regulation_params)
flash[:notice] = t('partners.regulations.updated')
redirect_to partners_root_path
else
add_breadcrumb t('partners.regulations.edit')
render :edit
end
end
protected
def set_regulation
#rental_company_regulation = Regulation.where(rental_company_id: rental_company).first
end
def set_breadcrumbs
add_breadcrumb current_partner.rental_company.name, :partners_root_path
end
private
def regulation_params
params.require(:regulation).permit(:content_pl, :content_en, :rental_company_id)
end
end
end
Creating resource from scratch works properly. But I went to:
"http://localhost:3000/partners/regulations/4/edit" to edit regulation I have the following error:
undefined method `partners_regulation_path' for #<#<Class:0x0000000242fae8>:0x00000007d9afb0>
I can't solve this problem. What's wrong?
Edit:
Rake routes:
partners_rental_company_regulation_index GET /partners/regulations(.:format) partners/regulations#index
POST /partners/regulations(.:format) partners/regulations#create
new_partners_rental_company_regulation GET /partners/regulations/new(.:format) partners/regulations#new
edit_partners_rental_company_regulation GET /partners/regulations/:id/edit(.:format) partners/regulations#edit
partners_rental_company_regulation PATCH /partners/regulations/:id(.:format) partners/regulations#update
Edit2:
I've changed my form too looks like this:
= horizontal_simple_form_for [:partners, #regulation], url: partners_rental_company_regulation_path
Now I can edit exisiting resource but can't create a new one. When I trying to create the new one I have the following error:
No route matches {:action=>"update", :controller=>"partners/regulations"} missing required keys: [:id]
What's wrong?
as
To simplify user2675613's answer, your error is basically caused by using the as argument in your routes
as: basically allows you to "name" the route:
#config/routes.rb
resources :users # -> users_path
resources :users, as: :members # -> members_path
Error
Your error is as follows:
undefined method `partners_regulation_path'
This basically means you're using a path which doesn't exist. This is because you've used the as: option in your routes:
#config/routes.rb
resources :partners do
resources :regulations #-> partners_regulation_path
end
resources :partners do
resources :regulations, as: "test" # -> partners_test_path
end
This is confirmed with your routes:
partners_rental_company_regulation_index
new_partners_rental_company_regulation
edit_partners_rental_company_regulation
partners_rental_company_regulation
Fix
The way to fix this is to remove the as: option from your routes:
#config/routes.rb
resources :partners do
resources :regulations #-> partner_regulations_path
end
Alternatively, if you wanted to keep the custom name for your paths, you'll have to change your path references to parental_company_regulation_path
As you can see you in your rake routes your url to edit a regulation is edit_partners_rental_company_regulation GET /partners/regulations/:id/edit(.:format) and to create a new one the url is new_partners_rental_company_regulation GET /partners/regulations/new(.:format).
You need to change the way you are using your form here. You can create a partial for all the common fields of form but you need to separate the url part in your form to make a create and update requests.
You can make a partial _form.html.haml with contents:
= f.error_notification
%ul.nav.nav-pills
%li
= link_to image_tag("flag_pl.png"), '#PL', class: 'regulation_pl'
%li
= link_to image_tag("flag_en.png"), '#EN', class: 'regulation_en'
.polish_regulation
%h1.page-header
= t('partners.regulations.polish')
= f.input :content_pl, :as => :ckeditor, :input_html => { :ckeditor => {:toolbar => 'Pure', width: 750} }, error: false
.english_regulation
%h1.page-header
= t('partners.regulations.english')
= f.input :content_en, :as => :ckeditor, :input_html => { :ckeditor => {:toolbar => 'Basic', width: 750} }, error: false
Then inside your edit.html.haml you can have:
= content_for :heading, t('partners.regulations.edit')
.row
.col-md-6
= horizontal_simple_form_for [:partners, #regulation], url: partners_rental_company_regulation_path do |f|
= render :partial => "form", :locals => { :f => f } #you need to pass other required locals too else it'll give error
= f.submit t('actions.save_changes'), class: "btn btn-lg btn-default"
Similarly inside your new.html.haml you can have:
= content_for :heading, t('partners.regulations.new')
.row
.col-md-6
= horizontal_simple_form_for [:partners, #regulation], url: partners_rental_company_regulation_index_path do |f|
= render :partial => "form", :locals => { :f => f } #you need to pass other required locals too else it'll give error
= f.submit t('partners.regulations.save'), class: "btn btn-lg btn-default"

Rails GET not translating slugged id with extra parameters

I have a model which is linking to the show method:
<%= link_to "View Others", :controller => "browse",
:action => "show", :id => #id, :d => "25" %>
Clicking the link gives:
http://localhost:3000/browse/santa-cruz?d=25
Rails gives the error though:
No route matches {:controller=>"browse", :action=>"show", :id=>nil, :d=>"25"}
If I take the extra parameter off everything works.
<%= link_to "View Others", :controller => "browse",
:action => "show", :id => #id %>
Goes to http://localhost:3000/browse/santa-cruz
This page loads and I am getting the correct params[:id]
Any ideas?
Pasted bellow is the show for my controller
def show
if params[:d].nil? then
# Show list of addresses in city.
addresses = Address.where(:slug => params[:id])
profile = []
addresses.each do |ad|
profile << ad.profile
end
unless profile.blank?
#profile = Kaminari.paginate_array(profile).page(params[:page]).per(5)
#title = "Profiles Near " + addresses.first.city
#id = params[:id]
else
redirect_to :controller => 'pages', :action => 'notlaunched', :zip => params[:id]
end
else # :d exists
# show all within :d miles.
addresses = Address.where(:slug => params[:id])
nearby = Address.near("#{addresses.first.fulladdress}", params[:d], :order => :distance)
profiles = nearby.map{ |ad| ad.profile }.uniq
end
end
Here's the Index:
def index
cities = []
states = []
Address.find_each do |ad|
cities << { :city => ad.city, :slug => ad.slug } # slug becomes the :id of show
states << ad.state
end
#cities = cities.uniq
#states = states.uniq
#title = "Browse Cities"
end

How can I save the id of the new wishlist in the field `wishlist_id` of `wishlist_entry`?

I want to save the id of the wishlist in a wishlist_entry table in a column like wishlist_id.
I have an link_to element like this:
<%= link_to 'Create', new_wishlist_entry_path(:wishlist => #wishlist.id) %>
This gives me the following url:
http://localhost:3000/wishlist_entries/new?wishlist=36
The wishlist_entry_controller's new action is:
def new
#wishlist_entry = WishlistEntry.new
#wishlist = Wishlist.find(params[:wishlist])
respond_to do |format|
format.html # new.html.erb
format.json { render json: #wishlist_entry }
end
end
The create action is:
def create
#wishlist_entry = WishlistEntry.new(
:wishlist_id => Wishlist.find(params[:id]),
:entry_name => params[:wishlist_entry][:entry_name],
:description => params[wishlist_entry][:description]
)
I get this error:
Couldn't find Wishlist without an ID
app/controllers/wishlist_entries_controller.rb:44:in `create'
The error is in the link:
:wishlist_id => Wishlist.find(params[:id]),
Whats wrong? How can I save the id of the new wishlist in the field wishlist_id of wishlist_entry?
I think the problem is that the wishlist id is coming in params[:wishlist] not params[:id]. The error you are seeing in your controller is because params[:id] is nil and the Wishlist class doesn't know what to do with Wishlist.find(nil).
Try this:
def create
#wishlist_entry = WishlistEntry.new(
:wishlist_id => params[:wishlist]),
:entry_name => params[:wishlist_entry][:entry_name],
:description => params[wishlist_entry][:description]
)
Without knowing exactly what you're trying to do here, it looks like the problem is that wishlist_id isn't getting passed to your create action.
The best way to fix this is to take advantage of the nested resources you've already set up by changing
<%= link_to 'Create', new_wishlist_entry_path(:wishlist => #wishlist.id) %>
to
<%= link_to 'Create', new_wishlist_wishlist_entry_path(:wishlist => #wishlist.id) %>
(wishlist_wishlist_entry looks pretty bad, but you can change it by using :as => 'whatever' in your routes)
Then in your new action:
#wishlist = Wishlist.find(params[:wishlist_id])
In your form:
form_for([#wishlist, #wishlist_entry])
And in your create action:
#wishlist = Wishlist.find(params[:wishlist_id])
#wishlist_entry = #wishlist.wishlist_entries.build(params[:wishlist_entry])

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Resources