No Method Error on edit method - ruby-on-rails

I am trying to edit my events model. Here is what I have for the edit:
Edit Event
<%= form_for(#event) do |f| %>
<%= render 'fields', :f => f %>
<div class="actions">
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.label :description %><br />
<%= f.text_field :description %>
<%= f.submit "Update" %>
</div>
<% end %>
I made the route as so:
resources :events do
member do
post :attend
post "/remove_attendee/:user_id" => "events#remove_attendee", :as=>:remove_attendee
post "/edit" => "events#edit"
end
But I am getting a no method error. NoMethodError in Events#edit and it is on line 3 which is the form_for place. What am I doing wrong?

The error is not in your view, the form_for tag calls some methods on the resource passed in, in this case #event. Make sure that #event is not nil and that the lookup to pull up the resource is working as intended. Again, seeing you controller/model/etc. code along with the full error would help.

Check that you are setting #event in your controller.

Related

Routing for multiple controllers for a single resource in Rails 3.1

I asked a question similar to this one about a week ago, but this is a slightly different perspective on it. The nature of the question involves being redirected to the correct controller.
I have a single resource, posts, and I have 4 different categories these posts can be under. I want each of these categories to be particular to a single controllers, and so I have the following in my routes.rb:
resources "code", :controller => :code_posts, :as => :code
resources "sports", :controller => :sports_posts, :as => :sports
resources "gaming", :controller => :game_posts, :as => :gaming
resources "the-nation", :controller => :personal_posts, :as => :the_nation
So now I can access posts through URLs like, for example, /code/1, /sports/34 to access the same post resource, but with each controller focusing on a single scope, namely a particular category.
This is all well and good, but my issue comes up when I try to edit or save particular posts. I have the following partial _form.html.erb (rendered in the new and edit views) in all the view folders for their particular controller:
<%= form_for #post do |f| %>
<div class="field">
<%= f.label :author %><br/>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :title %><br/>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :category %>
<%= f.select :category_id, Category.all.collect {|c| [c.name, c.id] }, {:include_blank => true} %>
</div>
<div class="field">
<%= f.label :summary %><br/>
<%= f.text_area :summary, :rows => 5 %>
</div>
<div class="field">
<%= f.label :body %><br/>
<%= f.text_area :body %>
</div>
<div class="field">
<%= f.label :tag_tokens %><br/>
<%= f.text_field :tag_tokens, "data-pre" => #post.tags.map(&:attributes).to_json %>
</div>
<div class="field">
<%= f.submit "Submit" %>
</div>
<% end %>
So whenever I create or update a post, through whichever controllers, I always get redirected back to /posts/4, /posts/123, /posts/:id, whatever. I want to get redirected to the particular controller the post being edited or created lives under. So if I go to /code/new, and submit the new post, I want to be redirected to /code/1234, and not /posts/1234. How can I do this? For some reason I'm just having major mental mind blocks this morning. Thanks.
EDIT Updated <%= form_for #post do |f| %> to <%= form_for #post, :url => code_url(#post) do |f| %> and it works for /code/1/edit but not /code/new. When trying to access a new post form, I get the following error:
No route matches {:action=>"show", :controller=>"code_posts", :id=>#<Post id: nil, author: "Les Peabody", summary: nil, body: nil, created_at: nil, updated_at: nil, title: nil, category_id: 1, slug: nil>}
This is my CodePostsController#new method
def new
#post = Post.new(:category => Category.find_by_name("Programming"), :author => current_user.full_name)
end
You may specify the url in the form
<%= form_for #post, :url => gaming_path do |f| %>
You may use inheritance on the model.
The path in you form is determined by the class name, and in this case it is post.
If they mach with resources naming it should generate proper paths as well.
The dirty hack may be keeping objects path in it, I saw someone do that, but I do not recommend it too much.
I think the reason is the form_for method which takes for the update action as default the name of the parameter (here post) it gets.
So to change that, you have to add at the beginning (for the example resource code) the following:
<%= form_for #post, :url => code_path(#post) do |f| %>
This is of course only the URL for an existing object, the URL for a new object should be different. It should be there new_code_path (and no argument). So your partial should only contain the fields and labels, not the form_for call, because the URL should be different then.
You should look at the output of the call in the shell: bundle exec rake routes and search for the correct paths in the output.
So, ultimately what is important is how the form gets turned into HTML. If you look at the differences between a form that is meant for editing, and a form that is meant for a new object, there is only one thing that is ever really different that matters - the action URL.
In the case of a new form, the form tag should look something like:
<form accept-charset="UTF-8" action="/code" class="new_post" id="new_post" method="post">
and in the case of an edit form:
<form accept-charset="UTF-8" action="/code/1" class="edit_post" id="edit_post_1" method="post">
The only thing that matters to rails however is the name of the input elements (which are constant in both forms) and the action attribute in the form tag. That tells Rails whether or not it's rendering the edit or create action.
Since we're splitting up control of a single resource through multiple controllers, the standard form_for #post will not suffice since Rails can no longer automate the rendering process through convention (as we're doing a very unconventional thing). It is necessary to do some manual labor. The following will do the trick.
Convert the partial to the following:
<%= form_for #post, :url => path do |f| %>
<div class="field">
<%= f.label :author %><br/>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :title %><br/>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :category %>
<%= f.select :category_id, Category.all.collect {|c| [c.name, c.id] }, {:include_blank => true} %>
</div>
<div class="field">
<%= f.label :summary %><br/>
<%= f.text_area :summary, :rows => 5 %>
</div>
<div class="field">
<%= f.label :body %><br/>
<%= f.text_area :body %>
</div>
<div class="field">
<%= f.label :tag_tokens %><br/>
<%= f.text_field :tag_tokens, "data-pre" => #post.tags.map(&:attributes).to_json %>
</div>
<div class="field">
<%= f.submit "Submit" %>
</div>
<% end %>
The path variable in there is a variable passed in through the :locals mechanism in the partial render, like so:
new.html.erb
<%= render :partial => "form", :locals => {:path => code_index_path} %>
and edit.html.erb
<%= render :partial => "form", :locals => {:path => code_path(#post)} %>
The nice thing with this solution is you can DRY up the code too by placing _form.html.erb in app/views/layouts or app/views/posts and reuse it in all of the new and edit views for all controllers that manipulate the Post resource in a consistent fashion. So rather than having:
<%= render :partial => "form", :locals => {:path => code_path(#post)} %>
we have:
<%= render :partial => "layouts/form", :locals => {:path => code_path(#post)} %>

Get the name of a parent resource when working with a nested resource

I have a comment controller that uses a form partial to add comments. Now this controller is nested under any parent resource that needs to have comments.
resource :post do
resource :comments
end
resource :poll
resource :comments
end
If I want to have a form partial that automatically configured for the proper resource how would I do it?
Right now I have to set up forms on the page of the nested resource like so:
<%= form_for [#post, #comment] do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
I would like to have a partial that looks something like the above code but that I can just call <%= render 'comments/form' %>
Any ideas on the best way to make this happen?
You can solve this problem by passing a local variable to the comments partial using the locals hash:
In your nested resource, lets say, post's view:
<%= render 'comments/form', :locals => {:resource => #post} %>
Your comments form :
<%= form_for [resource, #comment] do |f| %>
<%= f.label :title %>
<%= f.text_field :title %> <%= f.label :body %>
<%= f.text_area :body %> <%= f.submit %>
<% end %>
Also, I encourage you to go through this guide on partials where the details are explained.

undefined method "_index_path" form_for problem

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.

Order confirmation page in rails

I've been trying to create an order confirmation page for my rails app, and am not quite sure how to go about it in a restful way.
There were a few answers on this question that got me halfway there, but the problem was that I wasn't quite sure how to set up the form in the rails view so that it would take the user to a confirmation page with all their details instead of a create action.
Right now my view is simple:
<% form_for :order do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :first_name %><br />
<%= f.text_field :first_name, :size => 15 %>
</p>
<p>
<%= f.label :last_name %><br />
<%= f.text_field :last_name, :size => 15 %>
</p>
(Be sure to enter your name as it appears on your card)
<p>
<%= f.label :card_type %><br />
<%= f.select :card_type, [["Visa", "visa"], ["MasterCard", "master"], ["Discover", "discover"], ["American Express", "american_express"]] %>
</p>
<p>
<%= f.label :card_number %><br />
<%= f.text_field :card_number %>
</p>
<p>
<%= f.label :card_verification, "Card Verification Value (CVV)" %><br />
<%= f.text_field :card_verification, :size => 3 %>
</p>
<p>
<%= f.label :card_expires_on %><br />
<%= f.date_select :card_expires_on, :discard_day => true, :start_year => Date.today.year, :end_year => (Date.today.year+10), :add_month_numbers => true %>
</p>
<p><%= f.submit "Submit" %></p>
What things should I be doing to direct the user to a confirmation page that shows all the order details?
Thanks!
Kenji
There were a few answers on this
question that got me halfway there,
but the problem was that I wasn't
quite sure how to set up the form in
the rails view so that it would take
the user to a confirmation page with
all their details instead of a create
action.
Directing a form to a non standard page is pretty simple.
Add a url option form_for.
Such that
<% form_for :order do |f| %>
becomes
<% form_for :order :url => {:action => "confirm"} do |f| %>
You'll need to crate the confirm action in your routes, but that only involves this:
map.resources :orders, :collection => {:confirm => :get}
All you need now is a basic controller action and a view:
def confirm
#order = Order.new(params[:order])
unless #order.valid?
render :action => :new
else
end
end
Your view should look almost identical to the show view, with the addition of a form submitting #order to the create action.
Why don't you pull the confirmation via ajax for example, pull the result and put it as an overlay div, upon confirmation submit the original values in the form.
If you still need to do it your way then check wizardly, it's exactly designed for such uses.
I would like to update the answer for more elegant Rails 4 or up.
I hope it will help newbies like me. Ruby is awesome! :)
routes.rb
resources :orders do
collection do
post 'confirm'
end
end
orders_controller.rb
def confirm
#order = Order.new(order_params) # GET THE POST parameters
render :new if #order.invalid? # Return if false
end
form.html.erb
<%= form_for #order, url: {action: 'confirm'} do |f| %>

RESTful way to use form_for?

I am attempting to use form_for to implement a search form that works with a table-less Search model I created. The search form keeps triggering the 'index' action. I assume I should use 'new' to create the form and 'create' the process the search query. Looking at the log, my POST is getting changed into a GET. Here's my code:
/searches/new.html.erb:
<% form_for :searches, #search, :url => searches_path, :html => {:method => :post} do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :keywords %><br />
<%= f.text_field :keywords %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
What's the standard way for triggering the 'create' action with form_for?
Are you using the RESTful map.resources :searches ?
If so, shouldn't your :url be set to new_search_path ?
form_for is used with models. For a simple search form, I reccommend doing something like this:
<% form_tag posts_path, :method => :get do |f| %>
<%= f.text_field :query %>
<% end %>
You'll get /posts?query=wtf.

Resources