I'm trying to create a form where a user can type in their email and it will save it to the db. I want this form in the footer of every page.
I've generated NewsletterSignup via rails scaffolding.
Now i have this code in my /app/views/refinery/_footer.html.erb:
<%= form_for(#newsletter_signup) do |f| %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and when i try and load the page i get this error:
NoMethodError in Refinery/pages#home
Showing /Users/tomcaflisch/Sites/PersonalTrainingKT/app/views/refinery/_form.html.erb where line #1 raised:
undefined method `newsletter_signups_path' for #<#<Class:0x007fb84c769ba0>:0x007fb84c08d110>
Why is the method undefined? If i run rake routes i can see it exists:
newsletter_signups GET /newsletter_signups(.:format) newsletter_signups#index
POST /newsletter_signups(.:format) newsletter_signups#create
new_newsletter_signup GET /newsletter_signups/new(.:format) newsletter_signups#new
edit_newsletter_signup GET /newsletter_signups/:id/edit(.:format) newsletter_signups#edit
newsletter_signup GET /newsletter_signups/:id(.:format) newsletter_signups#show
PUT /newsletter_signups/:id(.:format) newsletter_signups#update
DELETE /newsletter_signups/:id(.:format) newsletter_signups#destroy
routes.rb
PersonalTrainingKT::Application.routes.draw do
resources :newsletter_signups
# This line mounts Refinery's routes at the root of your application.
# This means, any requests to the root URL of your application will go to Refinery::PagesController#home.
# If you would like to change where this extension is mounted, simply change the :at option to something different.
#
# We ask that you don't use the :as option here, as Refinery relies on it being the default of "refinery"
mount Refinery::Core::Engine, :at => '/'
end
I'm also creating a new object in the application_controller since this newsletter signup will be available on every page:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :instantiate_newsletter_signup
def instantiate_newsletter_signup
#newsletter_signup = NewsletterSignup.new
end
end
It looks like since refinerycms mounts the routes (not sure if that's correct terminology), it cannot see normal routes.
From this link https://groups.google.com/forum/#!topic/refinery-cms/5k7Co4D1bVI I figured out that i needed to change
<%= form_for(#newsletter_signup, :url => newsletter_signups_path, :method => :post) do |f| %>
to
<%= form_for(#newsletter_signup, :url => main_app.newsletter_signups_path, :method => :post) do |f| %>
Related
I'm having an issue very similar to the one asked in this question here: NoMethodError / undefined method `foobar_path' when using form_for However the answer there confuses me.
I went through Michael Hartel's Ruby on Rails tutorial before developing the application I'm working on at the moment, I tried to copy exactly what he did when he created a user model as I created my model. My application is designed to be a database for university professors, so the model I'm using is called "professor" but it's the same concept as "user".
Here is the code for my New.html.erb where is where users go to create a new professor:
<%provide(:title, 'Add a professor') %>
<div class="jumbotron">
<h2> New Professor</h2>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for (#professor) do |f| %>
<%= f.label "First Name" %>
<%= f.text_field :fname %>
<%= f.label "Last Name" %>
<%= f.text_field :lname %>
<%= f.label "School" %>
<%= f.text_field :school %>
<%= f.submit "Add this professor", class: "btn btn-primary" %>
<% end %>
</div>
</div>
</div>
And then here is the code from the Professor_controller.rb
class ProfessorController < ApplicationController
def show
#professor = Professor.find(params[:id])
end
def new
#professor = Professor.new
end
end
When I replace
<%= form_for (#professor) do |f| %>
In new.html.erb with:
<%= form_for (:professor) do |f| %>
It works. The thread I mentioned above said something about adding a route for the controller. My routes.rb looks like this:
Rails.application.routes.draw do
root 'static_pages#home'
get 'about' => 'static_pages#about'
get 'newprof' => 'professor#new'
resources :professor
And I don't believe that in Michael Hartel's book he does anything differently. I'm still very new to Rails so forgive me if this is a bit of an easy question, I've been stuck on it for a few days and I've tried numerous work arounds, using the instance of :professor works but #professor does not and I don't know why.
Within the Rails environment it's very important to be aware of the pluralization requirements of various names. Be sure to declare your resources as plural:
resources :professors
Declaring it in the singular may mess up the automatically generated routes, you'll get thing like professor_path instead of professors_path. You can check what these are with:
rake routes
If you get errors about x_path being missing, check that there's a route with the name x in your routes listing. The most common case is it's mislabeled, a typo, or you've failed to pluralize it properly.
I have a UsersController and it has below code
def sign_up
#user = User.new
end
And my view page has
<div class="col-md-6 col-md-offset-3">
<%= form_for #user do |f| %>
<%= f.label :first_name%>
<%= f.text_field :first_name %>
<%= f.label :last_name %>
<%= f.text_field :last_name %>
<%= f.submit "Register", class: 'btn btn-primary'%>
<% end %>
</div>
My routes.rb file contains the following entry
get 'signup' => 'users#sign_up'
But When I submit the form, it says
ActionView::Template::Error (undefined method `users_path' for #<#<Class:0x00000004d91490>:0x00000004d90220>)
Why does this throw an error and do I need to explicity point to url in the form_for?? Why is it so??
Change your routes to:
resources :users, only: [:new, :create], path_names: {new: 'sign_up'}
and rename your sign_up action back to new. The reason you are getting the error is rails trying to guess the correct url for given resource. Since you have passed #user, which is an instance of User class, it will try to call "#{#user.class.model_name.route_key}_path key, which results in the error you got.
To solve the issue you need either make your routes to define users_path or you need to specify the url directly using url option. users_path can be defined by either index or create action, so the above solution will work (and will not create remaining CRUD routes, yey!)
Try changing this line:
<%= form_for #user do |f| %>
to this:
<%= form_for(#user, url: 'signup') do |f| %>
I'm in need of some help regarding setting up the routing (I think that is the problem) for a view that is set up with bootstrap tabbed navigation. What I want to do is set up a form in each tab. Sounds easy enough.
However I can't figure out how the routing works when you want to submit two different actions (one to save to the db, and the other to get info from the db), each from their own tab. I can get it all to work perfectly if I give the "get_users" controller action a view, but when I try to bring it back together on the same page, just in different tabs, it goes a little awry and I'm not sure how to route correctly.
The two controller actions I have are:
class Users::RegistrationsController < Devise::RegistrationsController
def user_accounts
#user = User.new
end
def get_users
#users = User.search(params[:search]).paginate
(:per_page => 20, :page => params[:page] )
end
end
EDIT ------------------------------------
Include routes.rb - excluding the extra devise related routes. Can get the create_internal_user action working not the other. I understand that the routes are
incorrect as rails could never understand them. The first is correct, the second is simply what I would imagine it to look like if it were possible
# Authentication
as :user do
#add new internal users
get '/useraccounts' => 'users/registrations#user_accounts', as: 'new_internal_user'
post '/useraccounts' => 'users/registrations#create_internal_user', as: 'internal_user'
**# searching users - this is where I am uncertain**
get '/useraccounts' => 'users/registrations#get_users', as: 'get_internal_user'
post '/useraccounts' => 'users/registrations#get_users', as: 'getting_internal_user'
# other devise routes here
end
The view that renders them looks like this and renders two partials:
<div class="container">
<h1>User Accounts</h1>
<ul class="nav nav-tabs">
<li class="active">Add User</li>
<li>Edit User</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade in active" id="adduser">
<%= render 'users/registrations/create_internal' %>
</div>
<div class="tab-pane fade in" id="getusers">
<%= render 'users/registrations/get_users' %>
</div>
</div>
</div>
The two partials
_create_internal.html.erb
<%= form_for(resource, as: resource_name,
url: new_internal_user_path(resource_name)) do |f| %>
<div><%= f.label :email %><br />
<% for role in User::ROLES %>
<%= check_box_tag "user[roles][#{role}]", role,
#user.roles.include?(role),
{:name => "user[roles][]"}%>
<%= label_tag "user_roles_#{role}", role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
<div class="col-md-10 center"><%= f.submit "Create User",
class: "btn btn-primary"%></div>
<% end %>
_get_users.html.erb
<%= form_tag({:controller => "users/registrations", :action => "get_users"},
method: :get) do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div class="center" id="users">
<% if defined?(#users) %>
<%= render 'users/registrations/searchresults' %></div>
<%= will_paginate #users %>
<% end %>
I've spent many many hours trying to figure this out and just haven't been able to. Very new to Rails so this may be an easy question for someone. I've had a look at using AJAX, and resourceful routing, but as I'm still new I'm finding it a bit tough to wrap my head around it all at the one time. This is my first post on SO so apologies if I'm missing anything (please let me know).
Let's say your controller is UsersController and assuming your routes are not nested, this is how you create named routes:
get '/useraccounts', to: 'users#get_users' ## this route maps to the get_users action
post '/useraccounts' to: 'users#create_internal_user' # this route maps to the create_internal_user action
EDIT:
the format is controller_name#action_name. So make sure to replace users with your controllers name in plural
UPDATE:
if your controller's name is RegistrationsController
try:
get '/useraccounts', to: 'registrations#get_users'
post '/useraccounts' to: 'registrations#create_internal_user'
Looking at it, I think your error will likely be from your _get_users.html.erb partial.
Firstly, you're using form_for - why? Your use of form_for basically means you have to use the data inside #user to make it work, which I think will be causing the problem
I would use a form_tag as this does not persist your data:
<%= form_tag({:controller => "users/registrations", :action => "get_users"}, method: :get) do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
<% if defined?(#users) #-> this might need to be passed as a local var %>
<%= render 'users/registrations/searchresults' %></div>
<%= will_paginate #users %>
<% end %>
Routes
Your other problem is to do with your routes:
get '/useraccounts' => 'users/registrations#user_accounts', as: 'new_internal_user'
post '/useraccounts' => 'users/registrations#create_internal_user', as: 'internal_user'
**# searching users - this is where I am uncertain**
get '/useraccounts' => 'users/registrations#get_users', as: 'get_internal_user'
post '/useraccounts' => 'users/registrations#get_users', as: 'getting_internal_user'
Tell me how you expect Rails to know the difference between get '/useraccounts and get /useraccounts? The fact is it can't
You'll need to split up the routes so they don't all use the same path. I would do this:
get '/useraccounts' => 'users/registrations#user_accounts', as: 'new_internal_user'
post '/useraccounts' => 'users/registrations#create_internal_user', as: 'internal_user'
**# searching users - this is where I am uncertain**
get '/search' => 'users/registrations#get_users', as: 'get_internal_user'
After much frustration I have solved my own problem. With help from Rich Peck I realised that I was essentially creating a view with two forms on it, and that the tabbed navigation didn't really mean anything to the problem.
So I really only needed the two routes:
# #add new internal users
get '/useraccounts' => 'users/registrations#user_accounts', as: 'user_accounts'
post '/useraccounts' => 'users/registrations#create_internal_user', as:
'create_internal_user'
And then in the controller just changed the user_accounts action to look like this:
def user_accounts
#user = User.new
if params[:search_button]
#users = User.search(params[:search]).paginate(:per_page => 15, :page => params[:page] )
end
end
Came about this discovery thanks to this question/answer here:
form_for with multiple controller actions for submit
In the end the problem wasn't what I thought it was and ended up being simple. Was certainly an interesting learning journey. Thanks for your help again Rich Peck.
I keep getting an error saying: undefined method `androids_path' for #<#:0x007ff5edcd5330>. It's saying the error is at line 1 in new.html.
The name of the model is Android and is at android.rb. Any advice on how to fix this?
In androidapps_controller.rb:
def new
#android = Android.new
end
In new.html I have:
<%= form_for(#android, validate:true) do |f| %>
<% #android.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<%= f.submit %>
<% end %>
routes.rb
Grabapp::Application.routes.draw do
root :to => 'iosapps#index'
get "static_pages/home"
get "static_pages/add"
get "static_pages/about"
devise_for :users
resources :iosapps
resources :androidapps
Add to your routes.rb:
resources :android
You're error is because you've asked form_for to do resource based routing!
<%= form_for(#android, validate:true) do |f| %>
But you didn't define the resource based routing required to make it work!
Your model and controller are not matched (Android vs AndroidApp), so need to specify the correct url in your form:
<%= form_for(#android, validate: true, url: androidapps_path) do |f| %>
<%= form_for(#android, validate:true) do |f| %> automatically sets up the correct HTTP method (normally POST or PUT) with the HTML markup for a form. It also assumes you have a url set up called /androids in the case of POST and /androids/:id in the case of PUT. So for this to work you need to tell rails to create the necessary routings. This is done by adding the following line in config/routes.rb namely resources :androids.
This is why is is better to match up your model and controller names, Rails can then automatically infer the correct controller actions based on the model name.
You need to read up a bit more on routing and how it works. Do it here: http://guides.rubyonrails.org/routing.html
I'm making a Rails app, and want to add an upload feature with allows users to upload multiple entries at once through an Excel spreadsheet as opposed to entering one entry at a time.
Ideally, I was hoping to add a separate Upload/Submit portion to the bottom of the new.html.erb file (the bold portion being the Upload HTML.erb):
...
<div class="actions">
<%= f.submit %>
</div>
<% end %>
**<div class="field">
Or Upload Multiple Entries <br />
<%= form_tag({:action => :upload}, :multipart => true) do %>
<%= file_field_tag 'multi_doc' %>
<% end %>
</div>**
Here is my routes.rb file:
Dataway::Application.routes.draw do
devise_for :users
resources :revenue_models do
get 'upload', :on => :collection
end
root :to => "home#index"
end
And my revenue_models_controller (haven't developed the action at all yet, now just a redirect):
...
def upload
redirect_to revenue_models_path
end
I have followed the rails guides for Uploading files as well as for Routing files and I keep getting an error when I attempt to open the /new view I have modified:
Routing Error
No route matches {:action=>"upload", :controller=>"revenue_models"}
Try running rake routes
When I run rake route, I get an entry for the upload action:
upload_revenue_models GET /revenue_models/upload(.:format) revenue_models#upload
In the end, what I would like to do is upload an excel file with multiple entries, parse it, and conditionally add each data row to my database, which I was under the impression I could specify in the upload action. Please help!
Please use form_for instead form_tag.
Second What is multi_doc is a field/attribute of revenue_model?. I guess is a field/attribute of revenue_model.
Third, Where is your instance variable revenue_model in the form?
Fourth, You have to create first a instance variable of your Model, on your action/controller where you are showing the form, for example #revenue_model = RevenueModel.new.
After try this code:
<%= form_for(#revenue_model, :method => :get, :html => {:multipart => true}, :url => { :controller => "revenue_models", :action => "upload"})) do |f| %>
<%= f.file_field :multi_doc %>
<%= f.submit :id => "any_id" %>
<% end %>
The question is very confusing, trying to clarify your question specifying the name of your actions and the names of the files in your views.
Regards!