all. I'm following the carmen-rails documentation, though I'm using rails4, and I can't get the state subregion working when selecting a country. In fact, when leaving the subregion code in place I can't even navigate to the site. I get this error:
localhost:3000
Processing by OrdersController#new as HTML
Rendered orders/_subregion_select.html.erb (1.9ms)
Rendered orders/_form.html.erb (773.3ms)
Rendered orders/new.html.erb within layouts/application (775.8ms)
Completed 500 Internal Server Error in 784ms
ActionView::Template::Error (undefined method `downcase' for nil:NilClass):
1: <div id="order_state_wrapper">
2: <% parent_region ||= params[:parent_region] %>
3: <% country = Carmen::Country.coded(parent_region) %>
4:
5: <% if country.nil? %>
6: <em>Please select a country above</em>
app/views/orders/_subregion_select.html.erb:3:in `_app_views_orders__subregion_select_html_erb__937058573181156642_69893053026600'
app/views/orders/_form.html.erb:100:in `block in _app_views_orders__form_html_erb__3775537416523760398_69893046471120'
app/views/orders/_form.html.erb:1:in `_app_views_orders__form_html_erb__3775537416523760398_69893046471120'
app/views/orders/new.html.erb:6:in `_app_views_orders_new_html_erb__3931135682021831649_69893046299220'
Doesn't look like the (country, "US" in this case) paramater is being passed from the parent region because it's "nil". Any insight to get this working (I'm assuming with rails4) ?
app/views/orders/_form.html.erb
<div class="control-group">
<div class="field">
<%= f.label :country, 'Country' %>
<%= f.country_select :country, priority: %w(US CA), prompt: 'Please select a country' %>
</div>
<div class="field">
<%= f.label :state %><br />
<%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>
</div>
</div>
app/views/orders/_subregion_select.html.erb
<div id="order_state_wrapper">
<% parent_region ||= params[:parent_region] %>
<% country = Carmen::Country.coded(parent_region) %>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state, parent_region) %>
<% else %>
<%= text_field(:order, :state) %>
<% end %>
</div>
app/assets/javascripts/orders.js.coffee
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$ ->
$('select#order_country').change (event) ->
select_wrapper = $('#order_state_wrapper')
$('select', select_wrapper).attr('disabled', true)
country = $(this).val()
url = "/orders/subregion_options?parent_region=#{country}"
select_wrapper.load(url)
config/routes.rb
get '/orders/subregion_options' => 'orders#subregion_options'
# rake routes
Prefix Verb URI Pattern Controller#Action
orders_subregion_options GET /orders/subregion_options(.:format) orders#subregion_options
and when browsing to the subregion route directly and specifying a country:
http://localhost:3000/orders/subregion_options?parent_region=%22US%22
Started GET "/orders/subregion_options?parent_region=%22US%22" for 192.168.122.1 at 2013-07-08 13:20:21 -0400
Processing by OrdersController#subregion_options as HTML
Parameters: {"parent_region"=>"\"US\""}
DEPRECATION WARNING: Relation#first with finder options is deprecated. Please build a scope and then call #first on it instead. (called from service at /usr/local/rvm/rubies/ruby-2.0.0-p195/lib/ruby/2.0.0/webrick/httpserver.rb:138)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered orders/_subregion_select.html.erb (0.2ms)
Completed 200 OK in 4ms (Views: 1.3ms | ActiveRecord: 0.2ms)
The gem carmen-rails isn't registered on http://ready4rails4.net/, on the github page it written
carmen-rails is a Rails 3 plugin that supplies two new form helper methods: country_select and subregion_select.
plus on travis-ci.org https://travis-ci.org/jim/carmen-rails all builds are done with rails 3.2.
I would say the gem isn't Rails 4 ready maybe.
You should open an issue on the github page.
After having looked at your comment I have checked out the fork you're using and excepted the branch name I didn't saw any Rails 4 related commits.
Having a look at the changelog file (https://github.com/freerunningtechnologies/carmen-rails/blob/master/CHANGELOG.md) make me thinking that the rails 4 compatibility isn't done yet, but maybe I'm wrong.
I got the same error on my Rails 3.2.15 application. I had to make one small change to the Carmen gem in order for it to work. Follow these instructions and you should be golden:
In terminal at your project root, use bundle open carmen to open the Carmen gem library.
Find the file lib/carmen/querying.rb.
Replace line 15 with the following:
code = code.try(:downcase) # Codes are all ASCII
I've submitted a pull request to the original author so this might get fixed soon in the master branch, but until then you can do the above or you can use my fork in your gemfile as follows:
gem 'carmen', github: 'joshuapinter/carmen'
Figured something that is causing of your error I also ran out.
<div id="order_state_code_wrapper">
<% parent_region ||= params[:parent_region] %>
<% unless parent_region.nil? %>
<% country = Carmen::Country.coded(parent_region) %>
<% end%>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state_code, parent_region) %>
<% else %>
<%= text_field(:order, :state_code) %>
<% end %>
</div>
You need to add this to remove error
<% unless parent_region.nil? %>
<% country = Carmen::Country.coded(parent_region) %>
<% end%>
unless is necessary on page load first time parent_region is nil that time
and remove /orders from url and routes since it is not calling controller action subregion_options and using subregion_options as id
modified url and routes
url = "/subregion_options?parent_region=#{country}"
get '/subregion_options' => 'orders#subregion_options'
Related
I have been hitting my head against a brick wall so it is time to seek smarter people.
I am trying to create multiple records of one model using form_tag and fields_for. I have been following all the help/issues/guides I can find but it doesn't seem to work for me. I am wondering if it something that changed going to Rails 5 but more likely it is me.
Basically I want a new/create version of the task system listed at the bottom of the api page, similar to this guys puppy creator.
The "new" page loads fine with as many records as I like, so that part is ok but it doesn't seem to be creating a collection to send through, it is just overriding and thus sending through the last set of params so only creating one record.
What I have.
# routes
resources :container_returns
controller
# container returns controller
def new
#containers = Container.where(id: params[:container_ids])
#container_returns = []
#containers.each do |container|
#container_returns << ContainerReturn.new(
{
container_id: container.id,
quantity: container.amount,
uom: container.uom,
material_restriction_id: container.material_restriction_id
}
)
end
end
view
# new.html.erb
<%= form_tag container_returns_path, method: :post do %>
<% #container_returns.each do |container_return| %>
<%= fields_for 'returns[]', container_return, hidden_field_id: true do |cr| %>
<div class="field">
<%= cr.label :container_id %>
<%= cr.number_field :container_id %>
</div>
<div class="field">
<%= cr.label :material_restriction_id %>
<%= cr.number_field :material_restriction_id %>
</div>
<div class="field">
<%= cr.label :quantity %>
<%= cr.text_field :quantity %>
</div>
<div class="field">
<%= cr.label :uom %>
<%= cr.text_field :uom %>
</div>
<% end %>
<% end %>
<%= submit_tag "lots of returns" %>
<% end %>
which submits
# params submitted
Started POST "/container_returns" for 127.0.0.1 at 2018-10-19 11:00:48 +0200
Processing by ContainerReturnsController#create as HTML
Parameters: {
"utf8"=>"✓", "authenticity_token"=>[removed],
"returns"=>{"container_id"=>"405", "material_restriction_id"=>"", "quantity"=>"100.0", "uom"=>"kg"}, "commit"=>"lots of returns"
}
hopefully it is just something stupid that I missed.
UPDATE:
if I add an index to the form it now believes me that my objects are different and sends through all the params I need.
<% #container_returns.each_with_index do |container_return, index| %>
<%= fields_for 'returns[]', container_return, index: index do |cr| %>
[...]
as mentioned in the update, if I add an ID to the initial create it builds the correct array that I was expecting. What I also found was if I send through an index position that also works.
<% #container_returns.each_with_index do |container_return, index| %>
<%= fields_for 'returns[]', container_return, index: index do |cr| %>
[...]
gives me what I was expecting
Parameters: {
"returns"=>{"0"=>{"container_id"=>"400",...},
"1"=>{"container_id"=>"401",...},
etc.
},
"commit"=>"lots of returns"
}
I am making a rails application. After a user has registered (I have
already created user registration with devise), they can fill out this
form that will contain their profile information. The form should
submit a post request to the create action in the informations controller, but for some reason I can't configure the routes properly. When i run rake routes, for informations#create, which is what the form should be going to, it has a blank path. There is also informations#index, which is what I guess its going to now. How do I get the form to go to informations#create if the path is blank? I have done this several times, and i can't find what is wrong. Here is the model:
class Information < ActiveRecord::Base
belongs_to :user
end
Here is the controller:
class InformationsController < ApplicationController
def new
#information = Information.new
end
def create
#information = Information.create(params[:information])
redirect_to student_path
end
def index
end
end
And here is the view for the new action.
<div class="span6 offset3 text-center">
<h1>Edit your information</h1>
<%= simple_form_for #information do |f| %>
<%= f.input :skills %>
<%= f.input :looking_for, :label => 'What help do you need?' %>
<%= f.input :my_idea %>
<%= submit_tag "Save", :class => "btn btn-primary btn-large" %>
<% end %>
</div>
Here is the line in the routes file:
resources :informations
I get the following error:
undefined method `information_index_path' for #<#:0x007f9c00c7b3e0>
Here is rake routes for the files
informations GET /informations(.:format) informations#index
POST /informations(.:format) informations#create
Here is my full stacktrace when trying to load the page that shows the form:
Started GET "/informations/new" for 127.0.0.1 at 2013-10-21 17:25:09 -0400
Processing by InformationsController#new as HTML
Rendered informations/new.html.erb within layouts/application (64.2ms)
Completed 500 Internal Server Error in 70ms
ActionView::Template::Error (undefined method `information_index_path' for #<#<Class:0x007ff03e8b34a0>:0x007ff03e8b23e8>):
2: <div class="span6 offset3 text-center">
3: <h1>Edit your information</h1>
4:
5: <% simple_form_for #information do |f| %>
6: <%= f.input :skills %>
7:
8:
app/views/informations/new.html.erb:5:in `_app_views_informations_new_html_erb__3172218935119285240_70334909089600'
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.7ms)
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (9.1ms)
Started GET "/informations/new" for 127.0.0.1 at 2013-10-21 17:25:09 -0400
Processing by InformationsController#new as HTML
Rendered informations/new.html.erb within layouts/application (8.3ms)
Completed 500 Internal Server Error in 13ms
ActionView::Template::Error (undefined method `information_index_path' for #<#<Class:0x007ff03e8b34a0>:0x007ff03e8708a8>):
2: <div class="span6 offset3 text-center">
3: <h1>Edit your information</h1>
4:
5: <% simple_form_for #information do |f| %>
6: <%= f.input :skills %>
7:
8:
app/views/informations/new.html.erb:5:in `_app_views_informations_new_html_erb__3172218935119285240_70334908978600'
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.0ms)
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.3ms)
Rendered /usr/local/rvm/gems/ruby-2.0.0-p247#firehose/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (14.0ms)
Your problem is related to the fact that the word information is both the plural and the singular form. Just like water, or paper, or evidence. Rails considers those words uncountable.
There are two things you can do: either name your model something else or edit the file config/initializers/inflections.rb like so:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.uncountable %w( information )
end
Your form should be for one single information object. Not for a collection of information objects. Note that i have changed simple_form_for #informations to simple_form_for #information
<div class="span6 offset3 text-center">
<h1>Edit your information</h1>
<% simple_form_for #information do |f| %>
<%= f.input :skills %>
<%= f.input :looking_for, :label => 'What help do you need?' %>
<%= f.input :my_idea %>
<%= submit_tag "Save", :class => "btn btn-primary btn-large" %>
<% end %>
</div>
Also your failure is not because rails didn't generate information_index_path. Its because the named route for information#index is informations_path. the path is generated wrongly because you are using collection of objects.
Not sure if this will help, but try adding a = in front of simple_form_for. so that it will have a <%= instead of <%
Fairly simple question, and I've seen lots of similar ones asked in my search, but none of the solutions I've read have worked so far. Not sure where I'm going wrong.
In my application I have Projects and Verifications. When viewing a particular Project, I need to be able to have a link to "Verify Project", which will send the user to a new Verification form. They will enter a variety of values, but I do not want them to have to select the Project that this Verification belongs to by hand -- I want to be able to pass the project_id directly alongside the values the user enters in the Verification form.
On my project view I have:
<%= link_to "Verify Project", new_verification_path(:project_id => #project.id ) %>
and then in the verifications controller:
def new
#verification = Verification.new(params[:verification])
#project = params[:project_id]
end
def create
#verification = Verification.new(params[:verification])
#verification.project = #project
end
but this yields this error:
Validation failed: Project does not exist, Project does not exist
How can I create my Verification with :project_id being grabbed from the previous page?
EDIT
From the Rails log:
(clicking Verify Project)
Started GET "/verifications/new?project_id=4" for 127.0.0.1 at
2013-09-10 04:02:56 +0200 Processing by VerificationsController#new as
HTML Parameters: {"project_id"=>"4"} Rendered
verifications/_form.html.erb (91.3ms) Rendered
verifications/new.html.erb within layouts/application (97.5ms)
Rendered layouts/_shim.html.erb (0.3ms) Account Load (0.2ms) SELECT
"accounts".* FROM "accounts" WHERE "accounts"."remember_token" =
'NuxEYIjeCYyFklN7EyHTDQ' LIMIT 1 Rendered layouts/_header.html.erb
(38.6ms) Rendered layouts/_footer.html.erb (0.3ms) Completed 200 OK
in 381ms (Views: 368.4ms | ActiveRecord: 2.7ms)
and then Create
Started POST "/verifications" for 127.0.0.1 at 2013-09-10 04:03:04
+0200 Processing by VerificationsController#create as HTML Parameters: {"utf8"=>"✓",
"authenticity_token"=>"sqUBXqA6y5oKCW1DFAi3sv8rQzm+tKjOYDdc/lvUS+c=",
"verification"=>{"verifier_name"=>"test", "checked_on(1i)"=>"2013",
"checked_on(2i)"=>"9", "checked_on(3i)"=>"10", "notes"=>"test"},
"commit"=>"Create Verification"} Account Load (0.2ms) SELECT
"accounts".* FROM "accounts" WHERE "accounts"."remember_token" =
'NuxEYIjeCYyFklN7EyHTDQ' LIMIT 1 (0.0ms) begin transaction
(0.1ms) rollback transaction Completed 422 Unprocessable Entity in
18ms
ActiveRecord::RecordInvalid (Validation failed: Project does not
exist, Project does not exist):
app/controllers/verifications_controller.rb:55:in `create'
EDIT 2
Here's the form for the Create action:
<%= form_for(#verification) do |f| %>
<% if #verification.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#verification.errors.count, "error") %> prohibited this verification from being saved:</h2>
<ul>
<% #verification.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="span6 offset3">
<div class="field">
<%= f.label :verifier_name %><br />
<%= f.text_field :verifier_name %>
</div>
<div class="field">
<%= f.label :checked_on %><br />
<%= f.date_select :checked_on %>
</div>
<div class="field">
<%= f.label :notes %><br />
<%= f.text_area :notes %>
</div>
<div class="actions">
<%= f.submit %>
</div></div></div>
<% end %>
Your new controller action is a bit off. You're assigning an actual id to the #project instance variable, rather that the Project object that corresponds to that id. Subsequently, you're passing an invalid id from your new view to your create action.
Fix things by properly assigning the #project instance variable in your new action:
def new
#verification = Verification.new(params[:verification])
#project = Project.find(params[:project_id])
end
Then, you'll need to do a proper lookup of the a Project object in your create action:
def create
#verification = Verification.new(params[:verification])
#verification.project = Project.find(params[:project_id])
#verification.save
end
Finally, add the project_id as parameter in your form via the hidden_field form helper tag:
# in your `create` form
<%= f.hidden_field :project_id, :value => #project.id %>
You need to be sure that your project id is passed back to your create method. You can look up the project as in zeantsol's answer, or you can just pass the project ID. But you need to make sure that the form you create in your "new" view passes the project id back to your create method (perhaps in a hidden field)
See this post to see an example of using a hidden field in your view:
Rails hidden field undefined method 'merge' error
I have Realization model:
# encoding : utf-8
class Realization < ActiveRecord::Base
attr_accessible :city, :street, :title, :work, :photo, :date
has_attached_file :photo
end
Controller:
# encoding : utf-8
class RealizationsController < ApplicationController
before_filter :admin_required, :except => [:index,:show]
# GET /realization/new
def new
#realization = Realization.new
#realization.date = Time.now.__send__(:to_date).to_s
end
# POST /realization
def create
#realization = Realization.new(params[:realization])
if #realization.save
redirect_to #realization, notice: 'realization was successfully created.'
else
render action: "new"
end
end
(...) others
View of form:
<%= form_for #realization, :html => { :multipart => true } do |f| %>
<% if #realization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#realization.errors.count, "error") %> prohibited this realization from being saved:</h2>
<ul>
<% #realization.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
(...)
<div class="field">
<%= f.file_field :photo %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
And routes :
resources :realizations
And WEBrick server info is that:
Started POST "/realizacje" for 127.0.0.1 at 2013-04-12 12:26:35 +0200
Processing by RealizationsController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zK5jP4ChBBY+R21TjrZkp4xGvCHViTFJ+8Fw6Og28YY=", "realization"=>{"title"=>"wwwwww", "street"=>"", "city"=>"", "work"=>"", "date"=>"2013-04-12"}, "commit"=>"Submit"}
(1.0ms) SELECT COUNT(*) FROM "realizations"
Realization Load (2.0ms) SELECT "realizations".* FROM "realizations" ORDER BY created_at DESC LIMIT 7 OFFSET 0
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Rendered realizations/index.html.erb within layouts/application (156.0ms)
Completed 200 OK in 340ms (Views: 333.0ms | ActiveRecord: 4.0ms)
While I use the form and push the submit it redirects/randers realizations/index without notice or errors even!
I have completely no idea why? Especialy that it worked before...
Maybe javascript added later on may be the reason?
Paperclip works well in update so it isn't it...
You might check your new action to see what you're passing in to the form_for.
You want to be passing in a brand new instance of your Realization model.
i.e. in the new action you should have a line that reads #realization = Realization.new
The reason I suggest this is because form_for calls a method (#new_record?) on the object you give it and will submit a post or put request depending on whether that method call returns true or false.
I've been trying to do this for the last 2 hours with no success, I'm sure it's something really simple :)
So, I have form where users can search things based on some keywords. Here's the form code:
<%= form_tag search_by_description_path,:method => "get" do %>
<div class="column span-3">
<label>Search</label>
</div>
<div class="column span-5">
<input type="text" name="search_keywords" id="search_keywords"/>
</div>
<div class="column span-6">
<%= collection_select :category,:id,Category.all,:id,:name,:include_blank => "Everything" %>
</div>
<div class="column span-3">
<%= submit_tag "search" %>
</div>
<% end %>
I have this in the routes.rb:
get "search_by_description" => "search#search_by_description",:as => "search_by_description"
I have this in the controller:
def search_by_description
category = params[:category_id]
kw = params[:search_keywords]
#results = Posts.where("description LIKE ?","%#{kw}%").page(params[:page])
end
Ignore the fact that I'm not keeping track of category_id. In my view I have this:
<%= render "results",:locals => {:results => #results} %>
<%= paginate(#results) %>
The problem is, the when I go to the second page, I don't see anything displayed. Looking in the console, I noticed something that for the 1st page, the following SQL gets generated:
SELECT "posts".* FROM "posts" WHERE (description LIKE '%lorem%') ORDER BY id LIMIT 25 OF
SELECT COUNT(*) FROM "posts" WHERE (description LIKE '%lorem%')
while for the second only:
SELECT COUNT(*) FROM "posts" WHERE (description LIKE '%lorem%') LIMIT 25 OFFSET 25
Please give me some suggestions, I don't want to resort to writing my own pagination :)
The root cause of this problem is ActiveRecord 3.0's bug, which will be fixed in ActiveRecord 3.1 https://github.com/rails/rails/commit/d5994ee
https://github.com/rails/rails/commit/28c73f0
And I did a monkeypatch on Kaminari to work with ActiveRecord 3.0 https://github.com/amatsuda/kaminari/blob/9d0eebe38e2a22fb8100e491a6d94839d76c868f/lib/kaminari/models/active_record_relation_methods.rb#L7-11
In short, updating your Kaminari gem to the newest one will fix your problem. Thanks!
It was a bug, or misuse, from my side. I had this in my view:
<% if results.size > 0 %>
...
<% else %>
<p>No results found</p>
<% end %>
and this was always going on the else clause for pages different than the first. If I change the results.size to results.all.size it works. However, I don't understand why it doesn't work directly with results.size.