Ruby on Rails Tutorial (Book) Chapter 7 (3rd Edition) - No route matches [POST] "/signup" - railstutorial.org

I'm getting an 'No route matches [POST] "/signup"' error when in Chapter 7, I try to submit the signup form.
These are my routes:
root_path GET / static_pages#home
help_path GET /help(.:format) static_pages#help
about_path GET /about(.:format) static_pages#about
contact_path GET /contact(.:format) static_pages#contact
signup_path GET /signup(.:format) users#new
login_path GET /login(.:format) sessions#new
logout_path GET /logout(.:format) sessions#destroy
users_path GET /users(.:format) users#index
POST /users(.:format) users#create
new_user_path GET /users/new(.:format) users#new
edit_user_path GET /users/:id/edit(.:format) users#edit
user_path GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sessions_path POST /sessions(.:format) sessions#create
new_session_path GET /sessions/new(.:format) sessions#new
session_path DELETE /sessions/:id(.:format) sessions#destroy
This is my Users controller:
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to users_path(#user)
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
And this is the view where the signup gets posted from:
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for #user do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control' %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>
</div>
</div>
Here is my routes file:
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
resources :users
resources :sessions, only: [:new, :create, :destroy]
end

Place your resources at the top of the routes.rb file, here is my routes.rb:
Rails.application.routes.draw do
resources :users
resources :sessions, only: [:new, :create, :destroy]
root 'static_pages#home'
match '/signup' , to: 'users#new' , via: 'get'
match '/login' , to: 'sessions#new' , via: 'get'
match '/logout' , to: 'sessions#destroy' , via: 'delete'
match '/help' , to: 'static_pages#help' , via: 'get'
match '/about' , to: 'static_pages#about' , via: 'get'
match '/contact' , to: 'static_pages#contact', via: 'get'
end
Instead of:
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
resources :users
resources :sessions, only: [:new, :create, :destroy]
end

Chapter 7 doesn't have any references to sessions.
That happens in Chapter 8.
This is how the routes look like at the end of Chapter 7.
Rails.application.routes.draw do
root 'static_pages#home'
get 'about' => 'static_pages#about'
get 'help' => 'static_pages#help'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
resources :users
end

Related

how search with simple_form_for and pg_search gem

Rails : 5.1.4
I'm trying to search on :immo_type or/and :address
class SearchesController < ApplicationController
def home
#search = Purchase.find(params[:immo_type])
#purchases = Purchase.where("immo_type ILIKE ?", "%#{#search}%")
end
def index
#purchases = Purchase.all
#spurchases = Purchase.search_by_immo_type_and_address('#search')
end
end
From the view i used simple_form_for. I don't know how to see how to access the content of params[:immo_type]. When i used rails, i've this message
Couldn't find Purchase with 'id'=
I can see all my purchases with Purchase.all
<%= simple_form_for :immo_type, url: searches_url, method: :get do |f| %>
<%= f.hidden_field :immo_type, params[:immo_type] %>
<%= f.input :address, placeholder: 'Town', label: "Where" %>
<%= f.input :immo_type, placeholder: 'flat, house', label: "Flat or house" %>
<%= f.button :submit, "Rechercher", class: "btn btn-danger" %>
<% end %>
Here my models
class Purchase < ApplicationRecord
include PgSearch
pg_search_scope :search_by_immo_type_and_address, against: [:immo_type, :address]
belongs_to :user
has_many :users, :through => :searches
end
class Search < ApplicationRecord
belongs_to :user
belongs_to :leasing
belongs_to :purchase
end
I would like to search from my home.html.erb (root pages) and display the result on my index.html.erb
SearchesIndex
<ul>
<% #purchases.each do |purchase| %>
<li><%= link_to purchase.address %></li>
maison ou appartement : <%= purchase.immo_type %><br>
prix : entre <%= purchase.price_min %> et <%= purchase.price_max %><br>
<% end %>
</ul>
So, first i need to work with a search controller with the home and index views
class SearchesController < ApplicationController
def home
#searches = params[:immo_type]
end
def index
#purchases = Purchase.search_by_immo_type_and_address("#{params[:purchase][:immo_type]}")
end
end
This is my purchase model with Pg_Search gem
class Purchase < ApplicationRecord
belongs_to :user
has_many :users, :through => :searches
include PgSearch
pg_search_scope :search_by_immo_type_and_address, against: [:immo_type]
end
And the view with simple_form_for
<%= simple_form_for :purchase, url: searches_url, method: :get do |f| %>
<%= f.input :address %>
<%= f.input :immo_type %>
<%= f.button :submit, "Rechercher"%>
<% end %>
I hope it can help you !

Updating User password & email in separate forms but in same view

My goal is to create a profile page where the (logged in) user can choose to either update their email or their password (in separate forms so not both at the same time) without navigating away from the page.
Updating one's email is as simple as entering their new email and hitting the "Save Changes" submit button.
Updating one's password requires the user to enter their old password, their new password, and a confirmation of their new password then hitting the "Update Password" button. The problem must be in the update_pwd method.
users_controller.rb
# ...
def edit # template: edit.html.erb
#user = User.find(current_user)
end
def update_email
#user = User.find(current_user)
if params[:commit] == 'Save Changes'
if #user.update_attributes(user_params_email)
redirect_to me_url
flash[:notice] = "Your changes have been saved"
else # either invalid or taken
render :edit
end
else
render :edit
end
end
def update_pwd
#user = User.find(current_user)
if params[:commit] == 'Update Password'
if #user.update_attributes(user_params_pwd) && User.find_by(username: current_user.username).try(:authenticate, params[:current_password])
redirect_to me_url
flash[:notice] = "Password updated!"
else
flash.now[:alert] = #user.errors.full_messages[0]
render :edit
end
else
render :edit
end
end
private
#def user_params
#params.require(:user).permit(:id, :username, :email, :password, :password_confirmation)
#end
def user_params_email
params.require(:user).permit(:email)
end
def user_params_pwd
params.require(:user).permit(:password, :password_confirmation, :current_password)
end
edit.html.erb
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_email'}) do |f| %>
<% if #user.errors.any? %>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
<% end %>
<p> Current Email: <%= current_user.email %> </p>
<p> New Email: <%= f.text_field :email %> </p>
<%= f.submit "Save Changes" %>
<% end %>
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_pwd'}) do |g| %>
<p>Old Password<br>
<%= password_field_tag :current_password, params[:password] %></p>
<p>New Password<br>
<%= g.password_field :password %></p>
<p>Confirm New Password<br>
<%= g.password_field :password_confirmation %></p>
<%= g.submit "Update Password" %>
<% end %>
routes.rb
# ...
get '/me' => 'users#edit'
patch '/me' => 'users#update_email'
patch '/me' => 'users#update_pwd'
# ...
Now, I've been able to get the email updating to work as desired (with the necessary error messages/validations and so forth) but whenever the update password button is clicked, the view is rendered but nothing happens. Instead, it seems as if the update_email function is being called:
Started PATCH "/me" for ::1 at 2015-05-20 10:34:31 -0500
Processing by UsersController#update_email as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"msEsj6yxfdrbXjjdm6cH3JamrFU8R1EoZ5asmE831GSxLwpiiIW/wmGrr9HiQxFDySJtW5MKK6Ezq9hZaMNFtA==", "current_password"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Password"}
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1←[0m [["id", 2]]
DEPRECATION WARNING: You are passing an instance of ActiveRecord::Base to `find`. Please pass the id of the object by calling `.id`. (called from update_email ...)
user.rb
# ...
has_secure_password
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
validates_uniqueness_of :email
validates :password, length:{ minimum: 8 }, on: :create
validates :password_confirmation, presence: true, on: :create
# ...
application_controller.rb
# ...
helper_method :current_user
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
Error log (as seen above)
Started PATCH "/me" for ::1 at 2015-05-20 10:34:31 -0500
Processing by UsersController#update_email as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"msEsj6yxfdrbXjjdm6cH3JamrFU8R1EoZ5asmE831GSxLwpiiIW/wmGrr9HiQxFDySJtW5MKK6Ezq9hZaMNFtA==", "current_password"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Password"}
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1←[0m [["id", 2]]
DEPRECATION WARNING: You are passing an instance of ActiveRecord::Base to `find`. Please pass the id of the object by calling `.id`. (called from update_email ...)
You can try the following, I think this will help.
Please revert back if you face any issue.
routes.rb
get '/me' => 'users#edit'
patch '/me' => 'users#update_data'
edit.html.erb
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_data'}) do |f| %>
<% if #user.errors.any? %>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
<% end %>
<p> Current Email: <%= current_user.email %> </p>
<p> New Email: <%= f.text_field :email %> </p>
<%= f.submit 'Save Changes', name: 'update_email' %>
<% end %>
<%= form_for(current_user, :url => {:controller => 'users', :action => 'update_data'}) do |g| %>
<p>Old Password<br>
<%= password_field_tag :current_password, params[:password] %></p>
<p>New Password<br>
<%= g.password_field :password %></p>
<p>Confirm New Password<br>
<%= g.password_field :password_confirmation %></p>
<%= g.submit 'Update Password', name: 'update_password' %>
<% end %>
users_controller.rb
def edit
#user = User.find(current_user)
end
def update_data
#user = User.find(current_user)
if params[:commit] == "update_email"
if #user.update_attributes(user_params_email)
flash[:notice] = "Your changes have been saved"
redirect_to me_url
else
render :edit
end
elsif params[:commit] == "update_password"
if #user.update_attributes(user_params_pwd) && User.find_by(username: current_user.username).try(:authenticate, params[:current_password])
flash[:notice] = "Password updated!"
redirect_to me_url
else
flash.now[:alert] = #user.errors.full_messages[0]
render :edit
end
else
render :edit
end
end
private
def user_params_email
params.require(:user).permit(:email)
end
def user_params_pwd
params.require(:user).permit(:password, :password_confirmation, :current_password)
end

Devise Registration not showing "some" nested form fields Rails 4

I've got a modified Devise "sign_up" form (new registration) that includes fields for child and grandchild objects to be created along with the user. All of the model relationships are set up properly with access to the child's attributes. However, when the form renders, only the fields for the Devise user and one of the grandchildren is shown.
When a User is created, he/she will automatically be assigned a Customer object, an Account object, and an Address object. As you can see by the relationships in the User model below, User has one Customer and Customer has many Accounts and one Address. There was previously an issue with rendering the form at all, which I solved by changing the values passed to the builder method. WHY WON'T THIS WORK??? This is what I have so far:
*user.rb
class User < ActiveRecord::Base
before_create :generate_id
# Virtual attribute for authenticating by either username or email
# This is in addition to a real persisted field like 'username'
attr_accessor :login
has_one :customer, :dependent => :destroy
has_many :accounts, through: :customer
accepts_nested_attributes_for :customer, :allow_destroy => true
accepts_nested_attributes_for :accounts, :allow_destroy => true
has_one :address, through: :customer
accepts_nested_attributes_for :customer, :allow_destroy => true
accepts_nested_attributes_for :address, :allow_destroy => true
has_one :administrator
validates_uniqueness_of :email, :case_sensitive => false
validates_uniqueness_of :id
validates :username,
:presence => true,
:uniqueness=> {
:case_sensitive => false
}
# User ID is a generated uuid
include ActiveUUID::UUID
natural_key :user_id, :remember_created_at
belongs_to :user
# specify custom UUID namespace for the natural key
uuid_namespace "1dd74dd0-d116-11e0-99c7-5ac5d975667e"
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :trackable, :validatable
# Generate a random uuid for new user id creation
def generate_id
self.id = SecureRandom.uuid
end
# Allow signin by either email or username ("lower" function might have to be removed?)
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions.to_h).first
end
end
end
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters
# GET /users/sign_up
def new
#user = User.new
build_resource({})
self.resource[:customer => Customer.new, :account => Account.new, :address => Address.new]
respond_with self.resource
end
def create
#user = User.new
# Override Devise default behavior and create a customer, account, and address as well
resource = build_resource(params[:sign_up])
if(resource.save)
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
render :action => "new"
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u|
u.permit(:username, :email, :password, :password_confirmation,
customer_attributes: [:title, :firstname, :lastname, :phone1, :phone2],
account_attributes: [:acct_type],
address_attributes: [:address1, :address2, :zip_code])
}
end
end
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
def after_sign_in_path_for(resource)
if current_user.role == 'admin'
adminview_administrator_path(current_user, format: :html)
else
accounts_path(current_user, format: :html)
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation,
customer_attributes: [:title, :firstname, :lastname, :phone1, :phone2],
account_attributes: [:acct_type],
address_attributes: [:address1, :address2, :zip_code]) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :email, :password) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) }
end
end
views/devise/registrations/new.html.erb
<h1>Create an account</h1>
<div class="panel panel-default" style="width: 50%; padding: 0 25px;">
<%= bootstrap_nested_form_for(resource, as: resource_name, url: user_registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<h3>User Info</h3>
<!-- fields for User object -->
<%= f.text_field :username, autofocus: true %>
<%= f.email_field :email %>
<%= f.password_field :password , autocomplete: "off"%>
<% if #validatable %>
<em>(<%= #minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
<!-- fields for Customer object -->
<%= f.fields_for :customer do |customer_fields| %>
<%= customer_fields.text_field :title %>
<%= customer_fields.text_field :firstname %>
<%= customer_fields.text_field :lastname %>
<%= customer_fields.text_field :phone1 %>
<%= customer_fields.text_field :phone2 %>
<% end %>
<!-- fields for Account object -->
<%= f.fields_for :account do |account_fields| %>
<%= account_fields.text_field :acct_type %>
<% end %>
<!-- fields for Address object -->
<%= f.fields_for :address do |address_fields| %>
<%= address_fields.text_field :address1 %>
<%= address_fields.text_field :address2 %>
<%= address_fields.text_field :zip_code %>
<% end %>
<br />
<div class="actions">
<%= f.submit "Create My Account", :class => "btn btn-info" %>
</div>
<% end %>
</div>
</div>
Again, the above view does render, but the form only displays the fields for Devise new user and the one field (acct_type) for the account fields. How to get the rest of form to display and create all of these things on submission? Everything I've tried and everything I've read leads me to think that there's a problem with Rails 4's strong_parameters not being able to recognize the permitted attributes (see above controllers) in an array. Could that be the issue? If so, how does one go about passing the parameters necessary to build all these things?
Could be problem with the routes?
routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :registrations => "registrations" }
devise_scope :user do
# authentication
post "/accounts/adminview" => "devise/sessions#new"
end
root 'home#index'
resources :administrators do
member do
get :adminview
end
end
resources :users do
resource :customers
resource :accounts
resource :addresses
end
resources :account_types, :accounts, :addresses, :administrators, :customers, :transaction_types, :transactions, :users
end
I've tried every combination of ways that I could find on SO. This has taken up days worth of valuable time. I don't see any reason why it can't work. Does anyone have a better way of doing this? Is there a gem that would help? I'm willing to tear Devise apart and rebuild if necessary.
F.Y.I. It's Rails 4 and Devise 3.4.1. I've also added nested_form gem, but it doesn't make a difference.
Thank you
If you raise your params in controller you probably see accounts_attributes instead account_attributes you are setting in permit at application_controller, try replace it.

Form with nested models with many to many through relationship "can't assign mass attributes" error

I am stuck on the error "Can't mass-assign protected attributes: user" for my form. I have a user that creates a family and other users through a single form. Currently I am trying to create the functionality to have the user create a new family and one new user in one form. I have the Cocoon gem installed and am using Rails 3.2.16. https://github.com/nathanvda/cocoon
The error is occuring on this line
families_controller.rb
def create
binding.pry
#user = current_user
#family = Family.new(params[:family]) <<<<<
The params are:
=> {"utf8"=>"✓",
"authenticity_token"=>"EqWGxK3Fuj2uYk3namWK9SbXLPRKSn6cReT7wQddG0E=",
"family"=>
{"name"=>"test Family",
"users_attributes"=>{"0"=>{"first_name"=>"jane", "last_name"=>"smith"}}},
"commit"=>"Create Family",
"action"=>"create",
"controller"=>"families"}
Models
user.rb
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :age_months, :height_inches, :weight_ounces
has_many :user_families
has_many :families, through: :user_families
end
family.rb
class Family < ActiveRecord::Base
attr_accessible :location, :name, :users_attributes, user_families_attributes
has_many :user_families
has_many :users, through: :user_families
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :user_families, :reject_if => :all_blank, :allow_destroy => true
end
View
families.new.html.erb
<%= form_for(#family) do |f| %>
<form class = 'form-horizontal' role = 'form'>
<div class='form-group'>
<%= f.label :name %>
<%= f.text_field :name, placeholder: 'Family Name' %>
</div>
<div class='form-group'>
<%= f.fields_for #new_user do |ff| %>
<%= label_tag :first_name %>
<%= ff.text_field :first_name, placeholder: 'First Name' %>
<%= label_tag :last_name %>
<%= ff.text_field :last_name, placeholder: 'Last Name' %>
<%= label_tag :age_months %>
<%= ff.number_field :age_months, placeholder: 'Enter Age' %>
<%= label_tag :height_inches %>
<%= ff.number_field :height_inches, placeholder: 'Height in Inches' %>
<%= label_tag :weight_ounces %>
<%= ff.number_field :weight_ounces, placeholder: 'Weight in Pounds' %>
<% end %>
</div>
<div class='actions'>
<%= f.submit %>
</div>
</form>
<% end %>
Controller
families_controller.rb
class FamiliesController < ApplicationController
def index
#families = Family.all
end
def show
#user = current_user
#family = Family.find(params[:id])
end
def new
#user = current_user
#family = Family.new(name: "#{#user.last_name} Family")
#family.users.build
#new_user = User.new
end
def edit
#family = Family.find(params[:id])
end
def create
#user = current_user
#family = Family.new(params[:family])
#family.users << #user
#family.save
redirect_to root_path
end
def update
#family = Family.find(params[:id])
#family.update_attributes(params[:family])
#family.save
redirect_to root_path(anchor: 'profile')
end
def destroy
#family = Family.find(params[:id])
#family.destroy
redirect_to families_path
end
end
Family and User are associated with 1-M relationship.
In your view families/new.html.erb
Change
<%= f.fields_for #new_user do |ff| %>
To
<%= f.fields_for :users, #new_user do |ff| %>

how to set selected value in <%= f.select_tag %> dropdown list, how?

i have a long list dropdown menu including all currencies, i want the last selected value to be the default selected value in the list.
i am using Rails 4.0.0 and ruby 2.0.0
i am not using a model, i am just using a controller. i have put the dropdown list options inside a helper.
form.html.erb
<div class="calculator">
<%= form_for :convertor, :url => {:controller => "converter", :action => "show" } do |f| %>
<%= f.label :from_currency %>
<%= f.select :from_currency, options_for_select(currencies, :selected => params[:from_currency]) %>
<%= f.text_field :amount, :placeholder => "Amount", id: "textfield" %>
<%= #amount %>
<br>
<%= f.label :to_currency %>
<%= f.select :to_currency, options_for_select(currencies, :selected => params[:to_currency].to_i ) %>
<%= #result %>
<br>
<%= f.submit "Calculate", class: "btn btn-large btn-primary", id: "submitButton" %>
<% end %>
</div>
the list options are loaded from a helper *<%= f.select :to_currency, options_for_select(currencies, :selected => params[:to_currency].to_i ) %>* with name currencies
the dropdown list, in a helper
def currencies
[
['United Arab Emirates Dirham (AED)', 'AED'],
['Netherlands Antillean Guilder (ANG)', 'ANG'],
['Argentine Peso (ARS)', 'ARS'],
['Australian Dollar (A$)', 'AUD'],
['Bangladeshi Taka (BDT)', 'BDT'],
['Bulgarian Lev (BGN)', 'BGN'],
['Bahraini Dinar (BHD)', 'BHD'],
]
end
what am i doing wrong here?
A couple of things:
options_for_select takes two arguments: the list of options and the value that you want selected.
You're passing through the value as a hash: :selected => params...
The parameter name is wrong.
In your controller, you're saying that the parameter is called this:
params[:convertor][:from_currency]
But in your view, you have params[:from_currency].
Therefore, the solution to this is to do this:
<%= f.select :from_currency, options_for_select(currencies, params[:convertor][:from_currency]) %>
This code works for me.
in application helper
module ApplicationHelper
def opts_for_select_cur
opts_for_select = [
['United Arab Emirates Dirham (AED)', 'AED'],
['Netherlands Antillean Guilder (ANG)', 'ANG'],
['Argentine Peso (ARS)', 'ARS'],
['Australian Dollar (A$)', 'AUD'],
['Bangladeshi Taka (BDT)', 'BDT'],
['Bulgarian Lev (BGN)', 'BGN'],
['Bahraini Dinar (BHD)', 'BHD'],
]
return opts_for_select
end
end
and in view
<script type="text/javascript">
$(document).ready(function(){
$('#st').change(function(){
var inputText = $('#st :selected').val();
$("#hidden_one").val(inputText);
$("a").attr("href", "?value="+inputText );
});
$('#aa').click(function(){
var inputText = $('#st :selected').val();
$("a").attr("href", "?value="+inputText );
});
});
<%= f.select :text, options_for_select(opts_for_select_cur, params[:value]), {}, { id: "st" } %>
<br>
<%= link_to "refresh",nil, id: "aa" %>
the result is a select box with selected value.
this can help
<%= f.label :from_currency %>
<% if #from_cur.present? %>
<%= f.select :from_currency, options_for_select(currencies, #from_cur) %>
<% else %>
<%= f.select :from_currency, options_for_select(currencies), :required => true %>
<% end %>
<%= f.text_field :amount, :placeholder => "Amount", :required => true, id: "textfield" %>
<br>
<%= f.label :to_currency %>
<% if #from_cur.present? %>
<%= f.select :to_currency, options_for_select(currencies, #to_cur), :required => true %>
<% else %>
<%= f.select :to_currency, options_for_select(currencies), :required => true %>
<% end %>
i appreciate.