undefined method "_index_path" form_for problem - ruby-on-rails

I'm trying to generate a form using the form_for helper in RoR but I am encountering what seems to be a routing error. Here are the relevant files:
models/equipment.rb
class Equipment < ActiveRecord::Base
attr_accessible :name, :tracking_number
validates :tracking_number, :presence => true,
:uniqueness => { :case_sensitive => true }
end
controllers/equipments_controllers.rb
class EquipmentsController < ApplicationController
def index
#equipments = Equipment.paginate(:page => params[:page])
end
def new
#equipment = Equipment.new
end
end
views/equipments/new.html.rb
<h1>Add an equipment</h1>
<%= form_for (#equipment) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %> <br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :tracking_number %><br />
<%= f.text_field :tracking_number %>
</div>
<%= f.submit "Add" %>
<% end %>
routes.rb
EquipmentTracking::Application.routes.draw do
root :to => "equipments#index"
resources :equipments
end
I don't see anything wrong but they output the following:
NoMethodError in Equipments#new
Showing /opt/ror/equipment_tracking/app/views/equipments/new.html.erb where line #2 raised:
undefined method `equipment_index_path' for #<#<Class:0xb6725a2c>:0xb6724640>
If I changed it to
<%= form_for (:equipment) do |f| %>
it seems to work ok. I'm also certain that the static variable #equipment is getting passed since
<%= #equipment %>
returns
#<Equipment:0xb685ece0>
I am at a loss here. I just did what I did while I was following the railstutorial.org book and I was able to finish the book.

I think your problem lies in your use of the word "equipments". If you open the Rails console run 'equipment'.pluralize you'll see that the plural of "equipment" is "equipment".
So I'd do a search through your project and replace any instance of "equipments" with "equipment" and I'd bet that would fix it.

Related

ActionController “No explicit conversion of Symbol into Integer” for new record in Rails 4.2.1

I'm trying to create #booking and #booking.build_passenger in form_for with nested attributes in Rails 4.2.1
The error I get:
As you see in the console at the bottom of the image:
1. params.require(:booking) returns a Hash-like params for #booking
2. params.class returns ActionController::Parameters
As the params seems to behave correctly, IMO the problem hides somewhere in the form:
<%= form_for #booking do |f| %>
<%= f.hidden_field :flight_id, value: params[:flight_id] %>
<%= render 'flights/flight_info' %>
<div class="field">
<b><%= f.label :num_tickets, "Tickets" %></b>
<%= f.select(:num_tickets, #num_tickets) %>
</div><br>
<h4>Passenger info:</h4>
<%= f.fields_for #booking.build_passenger do |pass| %>
<div class="field">
<%= pass.label :name %>
<%= pass.text_field :name %>
</div>
<div class="field">
<%= pass.label :email %>
<%= pass.email_field :email %>
</div>
<% end %>
<%= f.submit 'Book Flight!' %>
<% end %>
Booking model:
class Booking < ActiveRecord::Base
belongs_to :flight
belongs_to :passenger
accepts_nested_attributes_for :passenger
end
Question: Where and how do I have to edit my code for the app to start creating #booking instances + #booking.build_passenger()
Your booking_params needs to be something like:
def booking_params
params.require(:booking).permit(:flight_id, :num_tickets, passenger_attributes: [:id, :name, :email])
end

undefined method `[]' for nil:NilClass error in rails

I have 2 conotrollers and 3 models:
Models:
problem.rb
class Problem < ActiveRecord::Base
has_many :problemtags
has_many :tags, :through => :problemtags
end
tag.rb
class Tag < ActiveRecord::Base
validate :name, :presence => true
has_many :problemtags
has_many :problems, :through => :problemtags
end
problemtag.rb
class Problemtag < ActiveRecord::Base
belongs_to :problem
belongs_to :tag
end
problems_controller.rb
class ProblemsController < ApplicationController
def new
#all_tags = Tag.all
#new_problem = #problem.problemtags.build
end
def create
params[:tags][:id].each do |tag|
if !tag.empty?
#problem.problemtags.build(:tag_id => tag)
end
end
end
def problem_params
params.require(:problem).permit(:reporter_id, :status, :date_time, :trace_code)
end
tags_controller.rb
//tags_controller is generate with scaffold
And I have below code in problems view:
new.html.erb
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= collection_select(:tags, :id, #all_tags, :id, {}, {:multiple => true}) %>
</div>
<% end %>
when I run the project, the problem's view is show, but when I complete the textfields and select tags and then click on submit button, I get below error:
NoMethodError in ProblemsController#create
undefined method `[]' for nil:NilClass
Extracted source (around line #22):
#problem = #reporter.problems.build(problem_params)
params[:tags][:id].each do |tag|
if !tag.empty?
#problem.problemtags.build(:tag_id => tag)
end
I do not understand the problem. any one can describe the problem to me?
As stated by your answers, your issue is that you're not sending the right data to your controller (and consequently params[:tags] will be blank):
Form
You're firstly missing the form_builder object in your collection_select (so your tags will likely not be sent inside the correct params hash). Although this may be by design, you need to ensure you're passing the data properly:
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= f.collection_select(:tags, :id, #all_tags, :id, {}, {:multiple => true}) %>
</div>
<% end %>
Params
Secondly, we cannot see your form or params hash. This is vital, as your form needs to look like this:
<%= form_for #variable do |f| %>
<%= f.text_field :value_1 %>
<%= f.text_field :value_2 %>
<% end %>
This creates a params hash like this:
params { "variable" => { "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" }}}
This will be the core reason why your controller will return the [] for nil:NilClass error - you'll be referencing params which don't exist. You'll need to call params[:variable][:tags] as an example
If you post back your params hash, it will be a big help
You could try using validate :tag_id, :presence => true to check for presence of the needed params.
I found 2 problems in my code:
in new.index.html(in problem view), the submit button is in the form_for and I write the field_for outside the form_for and when I click on submit button, the params hash of tags didn't create.
In collection_select, I forgot to add the name parameter of tag.
Correct new.html.erb code:
<%= form_for #problem do |f| %>
status: <%= f.text_field :status %><br/>
datetime: <%= f.datetime_select :date_time %><br/>
trace code: <%= f.text_field :trace_code %><br/>
<%= fields_for(#new_problem) do |f| %>
<div class="field">
<%= f.label "All Tags" %><br>
<%= collection_select(:tags, :id, #all_tags, :id,:name, {}, {:multiple => true}) %>
</div>
<% end %>
<%= f.submit %>
<% end %>
Thanks for all of the answers.

rails: create posts using STI

I am using single tablable inheritance(STI) to create different types of articles.
But now I have problem while creating articles.(I can do it only in console).
Here are my models
Article.rb
class Article < ActiveRecord::Base
attr_accessible :content, :title
validates :title, :presence => true
end
And TutorialArticle.rb
class TutorialArticle < Article
attr_accessible :author
validates :author, :presence => true
end
Here is my _form
<%= form_for(#article) do |f| %>
<%= f.hidden_field :type %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<%= render :partial => "edit" + f.object.type.downcase, :locals=>{:f=>f} %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
But now I have a problem in article_controller.rb in create method
def create
# create the desired subtype based on the hidden field :type in the form
#article = Object.const_get(params[:article][:type]).new(params[:article])
if #article.save
flash[:notice] = "Successfully created post."
redirect_to #article
else
render :action => 'new'
end
end
Now when I fill in the form and press Create Article button, I get the folloiwing error
undefined method '[]' for nil:NilClass
I even tried to hard code to understand what is wrong
and if I try to change #article = Object.const_get(params[:article][:type]).new(params[:article])
to
#article = TutorialArticle.new(params[:article])
my create method doesn't save the article. it just redirects to create new article page.
Could you please help me to solve the problem?
Ok, the printing of params helped. Add this to your TutorialArticle model:
def self.model_name
return Article.model_name
end
This will make your forms pass article instead of tutorial_article, and the rest should work as expected. You'll need this override in all your other Article subclasses.

Virtual attribute allways nil in custom validation method

because I'm pretty new to Ruby on Rails I'll explain what I did. I've got a virtual attribute in my model called testing. I've defined it like this:
class Comment < ActiveRecord::Base
attr_accessor :testing
attr_accessible :user_name, :comment, :user, :testing
I then added custom method for custom validation like this:
validate :custom_validation
I also added the method, of course:
def custom_validation
# a bit of custom_validation
end
I then added a field in my form:
<%= form_for(#comment) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.hidden_field :post_id, :value => #post.id %>
<% if !signed_in? %>
<div class="field">
<%= f.label :user_name %>
<%= f.text_field :user_name, :class => "user_field" %>
</div>
<% else %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<% end %>
<div class="field">
<%= f.label :comment %>
<%= f.text_area :comment, :style => "height: 50px; width: 80%;" %>
</div>
<div class="field pin">
<%= f.label :testint %>
<%= f.text_field :testing, :class => "user_field" %>
</div>
<div class="buttons">
<%= f.submit "Speichern" %>
</div>
<% end %>
That's all I did. So please don't assume I did something else I didn't describe here, because I didn't ;)
My problem is, that my virtual field testing is always nil inside of my custom_validation method. Unless I run the validation in the console:
co = Comment.new
co.testing = "Hello"
co.valid?
I've checked using the logger. If I run via the console the testing-field isn't nil. If I run it via the browser, it is. It seems that the parameter is somehow not passed to the model correctly. I hope I just missed something really obvious. Hope you can help me.
Cheers,
Michael
It has to do with what's in your create or update actions. The scaffold generator will put in code to set real attributes, but does not call setter methods from attr_accessor.
add attr_reader :testing to your model!

Using a Nested-Model form as a Partial on a different models's page

I have a nested model form for PhotoAlbums. The form works fine via the standard html. But what I need to do is render it as a partial in another page it's erroring: "No route matches
{:action=>"create", :controller=>"photo_albums"}"
The models:
Projects
has_many :photo_albums
PhotoAlbums
belongs_to :project
has_many :photos
Photos
belongs_to :photo_album
Controller:
def create
#project = Project.find(params[:project_id])
#photoalbum = PhotoAlbum.create(params[:photo_album])
end
Here is the working form which loads and works find via HTML:
<% form_for [:project, #photoalbum], :html => { :multipart => true }
do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<% f.fields_for :photos do |builder| %>
<% if builder.object.new_record? %>
<%= builder.label :photo, "photo File" %>
<%= builder.file_field :photo %>
<% end %>
<% end %>
<% end %>
The issue I'm having, is that to render this form as a partial in a
view in another page. I'm using the following:
<% #photoalbum = PhotoAlbum.new %>
<%= render :partial => "photo_albums/form", :locals =>
{:photoalbum => #photoalbum} %>
I checked by Rake Routes, And I do have it there:
project_photo_albums POST /projects/:project_id/
photo_albums(.:format)
{:controller=>"photo_albums", :action=>"create"}
Thoughts? thank you
In your form you have:
form_for [:project, #photoalbum]
but it seems that your partial only gets the #photoalbum variable. What about the project variable?

Resources