Contact Form (SimpleForm) - Route not found/unable to autoload? - ruby-on-rails

I'm trying to install the contact page on my Ruby on Rails app. It seems straight forward enough, but after installing the mailer gems, and creating my controller with:
$ rails generate controller contact_form new create
I navigate to my contact URL (/contact_form/new), and it says
"Unable to autoload constant ContactFormController, expected
/home/ubuntu/workspace/app/controllers/contact_form_controller.rb to
define it"
Routes and controller are as follows:
routes.rb
get 'contact_form/new'
get 'contact_form/create'
resources :contact_forms
contact_form_controller.rb
class ContactFormsController < ApplicationController
def new
#contact_form = ContactForm.new
end
def create
begin
#contact_form = ContactForm.new(params[:contact_form])
#contact_form.request = request
if #contact_form.deliver
flash.now[:notice] = 'Thank you for your message!'
else
render :new
end
rescue ScriptError
flash[:error] = 'Sorry, this message appears to be spam and was not delivered.'
end
end
end
contact_form.rb
class ContactForm < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message
attribute :nickname, :captcha => true
# Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts.
def headers
{
:subject => "My Contact Form",
:to => "your_email#example.org",
:from => %("#{name}" <#{email}>)
}
end
end

Note that your class is named ContactFormsController and Rails is looking for ContactFormController. You need to pay careful attention to the pluralization in Rails.
Controllers are plural.
Models are singular.
Routes are plural in most cases.
The pluralization of classes must always match the file name.
So why is Rails looking for ContactFormController? Because your routes are not defined properly:
get 'contact_form/new'
get 'contact_form/create'
get 'contact_forms/new' is the proper route for a form to create a new resource. You don't create resources with GET so get rid of get 'contact_form/create'.
resources :contact_forms
Is actually all that you need.
So to fix this error you should:
rename contact_form_controller.rb -> contact_forms_controller.rb.
change your route definition.
request /contact_forms/new instead.

Related

Following Rails tutorial, undefined method 'create' for nil:NilClass, with nested resource

I'm following the Rails tutorial and making changes where appropriate, with the intention that my tutorial project will become a full-fledged production app after the completion of the tutorial.
I've run into a snag with the second model portion of the tutorial. Here is how I've written my second model.
In my policy.rb:
class Policy < ApplicationRecord
has_one :insured
end
In my insured.rb:
class Insured < ApplicationRecord
belongs_to :policy
end
In my routes.rb:
resources :policies do
resource :insured
end
In my insureds_controller.rb:
def create
#policy = Policy.find(params[:policy_id])
# next line is raising the error
#insured = #policy.insured.create(insured_params)
redirect_to #insured
end
private
def insured_params
params.permit(:name, :address, :phone, :email)
end
I've inspected the #policy object with render plain: #policy.inspect and can confirm that ActiveRecord is retrieving the policy correctly. When I inspect the attributes of #policy, using render plain: #policy.attribute_names.inspect, I don't see an insured attribute, which I thought Rails was supposed to automatically manage for me. In the tutorial, an article has_many :comments, and a comment is supposedly easily created and associated with the parent article with this call: #article.comments.create(comment_params). I also noticed that the tutorial uses params.require(:comment).permit(...) while I have to use params.permit(...), after inspecting the params hash I saw that the :insured attributes existed in the top-level of the hash, instead of being tied to an :insured key within the hash.
I tried manually saving and assigning the #insured object like so:
def create
#policy = Policy.find(params[:policy_id])
#insured = Insured.new(insured_params)
if #insured.save
#policy.insured = #insured
redirect_to #insured
end
end
Only to run into the following error in my .../insureds/new.html.erb:
<h1>New Insured</h1>
<h1><%= #policy.policy_number %></h2>
<%= render 'form' %>
<%= link_to 'Cancel', policy_path(#policy) %>
Which derives from my partial form .../insureds/_form.html.erb:
# the following line raises the error
<%= form_with model: #insured, local: true do |form| %>
# html omitted for brevity
<% end %>
Error: 'undefined method insureds_path'. This is weird because when I inspect the HTML I can see the form action for this view is /policies/[:id]/insured.
Sorry for the massive wall of text, I wanted to show you guys that I did try to figure out what is going wrong.
There is an error in your config/routes.rb file:
resources :policies do
# change it for:
collection do
get 'insured', to: 'policies#show_insured', as: 'show_policy_insured'
# maybe unnecessary to be here
# get 'insured/new', to: 'insureds#new', as: 'new_policy_insured'
# post 'insured/create', to: 'insureds#create', as: 'create_policy_insured'
# delete 'insured/delete', to: 'insureds#delete', as: 'delete_policy_insured'
end
end
# add resources here
resources :insureds
In policy_controller.rb:
def show_insured # 'policy/:id/insureds/
end
In insureds_controller.rb:
def show # '/insureds/:id'
end
def create
...
redirect_to show_policy_insured && return if #insured_policy
end
# before_filter or before_action
#policy = Policy.find(params[:id])
#insured_policy = #policy.insured
Check it and run this to see your routes:
$ bundle exec rake routes
get /policies/:id/insured => 'policies_controller#show_insured'
get /insureds/:id => 'insureds_controller#show'
get /insured/new => 'insureds_controller#new'
post /insureds/create => 'insureds_controller#create'
delete /insureds/:id/delete => 'insureds_controller#delete'
#maguri, that's not all necessary. The stumbling block I was running into was that Rails couldn't automatically determine the correct routes. When I provided my own urls in the form_with declarations, everything went smoothly.
Observe the following change in my _form.html.erb for the Insured model, which belongs_to Policy, which has_one Insured.
<%= form_with model: #insured, url: policy_insured_path(#policy) local: true do |form| %>
In my updated insureds_controller.rb file, using #Phlip's suggestion:
def create
#policy = Policy.find(params[:policy_id])
#insured = #policy.create_insured(insured_params)
if #policy.insured.save
redirect_to policy_insured_path(params[:policy_id])
else
render 'new'
end
end
This allows me to keep routes.rb clean and simple:
resources :policies do
resource: insured
end
Thank you for your answer, it helped me discover the problem was with my routes.

Rails 4 Route Parameters Defined by Keywords

We're trying to set up rails routes with the parameters separated by more then just forward-slash symbols.
As an example:
someexample.com/SOME-ITEM-for-sale/SOME-PLACE
For the following path we'd like to extract SOME-ITEM and SOME-PLACE strings as parameters whilst identifying which controller to run it all against with the "-for-sale/" part.
I've been playing with variations on :constraints => {:item => /[^\/]+/} constructs but without any success. Am I looking in the right place? Thanks!
UPDATE
In the end I went with this solution:
get ':type/*place' => 'places#index', as: :place , :constraints => {:type => /[^\/]+-for-sale/}
And then recovered the full "SOME-ITEM-for-sale" sting for parsing in the controller using
params[:type]
Hope that helps someone!
friendly_id is what you want:
#Gemfile
gem 'friendly_id', '~> 5.1.0'
$ rails generate friendly_id
$ rails generate scaffold item name:string slug:string:uniq
$ rake db:migrate
#app/models/item.rb
class Item < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
end
The above will give you a slug column, which FriendlyId will look up any requests you send to the app:
#config/routes.rb
resources :items, path: "" do
resources :places, path: "" #-> url.com/:item_id/:id
end
Although the params will still be id (unless you use the param option of resources, but FriendlyId will override both your routes and model to use the slug instead:
<%= link_to "Item Place", items_place_path(#item, #place) %> #-> url.com/item-name-information/place-name-information
Update
If you wanted to have a "dynamic" routing structure, you'll be able to use the following (this requires the history module of FriendlyId):
#config/routes.rb
#...
get '/:item_id/:place_id', to: SlugDispatcher.new(self), as: :item #-> this has to go at the bottom
#lib/slug_dispatcher.rb
class SlugDispatcher
#http://blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app/
##########################################
#Init
def initialize(router)
#router = router
end
#Env
def call(env)
id = env["action_dispatch.request.path_parameters"][:item_id]
slug = Slug.find_by slug: id
if slug
strategy(slug).call(#router, env)
else
raise ActiveRecord::RecordNotFound
end
end
##########################################
private
#Strategy
def strategy(url)
Render.new(url)
end
####################
#Render
class Render
def initialize(url)
#url = url
end
def call(router, env)
item = #url.sluggable_type.constantize.find #url.sluggable_id
controller = (#url.sluggable_type.downcase.pluralize + "_controller").classify.constantize
action = "show"
controller.action(action).call(env)
end
end
####################
end
This won't work out the box (we haven't adapted it for nested routes yet), but will provide you the ability to route to the appropriate controllers.
In the end we went with this solution:
get ':type/*place' => 'places#index', as: :place , :constraints => {:type => /[^\/]+-for-sale/}
The router command only gets activated if the :type parameter contains "-for-sale" in the string
And then we recovered the full "SOME-ITEM-for-sale" sting for parsing in the controller using
params[:type]
Hope that helps someone!

How to use friendly_id history with nested resources

I have User and Campaign models. I nest campaigns under users and URLs look like this:
http://localhost:3000/user-slug/campaign-slug
Routes:
resources :users, :path => '' do
resources :campaigns, :path => ''
end
Campaign model:
class Campaign < ActiveRecord::Base
...
extend FriendlyId
friendly_id :title, use: :history
...
end
My User model doesn't use history.
Campaign controller (from friendly_id guide):
class CampaignsController < ApplicationController
before_filter :find_campaign
def show
#campaign = Campaign.friendly.find(params[:id])
end
private
def find_campaign
#campaign = Campaign.friendly.find(params[:id])
# If an old id or a numeric id was used to find the record, then
# the request path will not match the post_path, and we should do
# a 301 redirect that uses the current friendly id.
if request.path != campaign_path(#campaign)
return redirect_to #campaign, :status => :moved_permanently
end
end
end
When I visit an old slug to trigger redirection I get this error:
ActionController::UrlGenerationError in CampaignsController#show
No route matches {:action=>"show", :controller=>"campaigns", :format=>nil, :id=>nil, :user_id=>#<bunch of other stuff in here>} missing required keys: [:id]
Not sure how I should tweak the redirect method to make it work.
Managed to get it to work with this:
def find_campaign
#campaign = Campaign.friendly.find(params[:id])
#user = #campaign.user
# If an old id or a numeric id was used to find the record, then
# the request path will not match the campaign_path, and we should do
# a 301 redirect that uses the current friendly id.
request_slug = params[:id]
if request_slug != #campaign.slug
return redirect_to user_campaign_path(#user, #campaign), :status => :moved_permanently
end
end
Instead of comparing the request path I compared the request slug which doesn't have the part before the slash. And I needed to redirect to the correct route user_campaign_path.

Trying to override controller in Thoughtbot's Clearance gem for Rails

I am using Clearance 1.1.0 gem with Ruby on Rails 4.0.1. I am trying to override the sessions controller to provide my own custom method. I have not been able to successfully get rails to use my controller.
/app/controllers/sessions_controller.rb
class SessionsController < Clearance::SessionsController
private
def flash_failure_after_create
flash.now[:notice] = translate(:bad_email_or_password,
:scope => [:clearance, :controllers, :sessions],
:default => t('flashes.failure_after_create', :new_password_path => new_password_path).html_safe)
end
end
I have tried a few different things inside my routes.rb file, and have been unsuccessful. I want to change the route sign_in.
get '/sign_in' => 'sessions#new', :as => 'sign_in'
Yields the following error.
You may have defined two routes with the same name using the :as
option, or you may be overriding a route already defined by a resource
with the same naming.
Any ideas? Thank you!
Edit: I made a mistake. I actually need sessions#create to use my controller. I'm trying to pass a different variable to the yaml file for the flash when the session login fails.
Edit 2: I the appropriate session#create line to to my routes. In my session controller, I copied and edited for testing the flash_failure_after_create method. It is not being called. So I then copy the create method over. Now, my create method is being called, but not my flash_failure_after_create method. To get it to be called, I had to have the create method copied from gem, and changed status.failure_message to directly call the flash_failure_after_create method. Is this some sort of bug with clearance?
routes.rb
post 'session' => 'sessions#create', :as => nil
sessions_controller.rb
class SessionsController < Clearance::SessionsController
def create
#user = authenticate(params)
sign_in(#user) do |status|
if status.success?
redirect_back_or url_after_create
else
#flash.now.notice = status.failure_message
flash.now.notice = flash_failure_after_create
render :template => 'sessions/new', :status => :unauthorized
end
end
end
private
def flash_failure_after_create
# Changed flash for easy testing
flash.now[:notice] = 'Ballz.'
#flash.now[:notice] = translate(:bad_email_or_password,
# :scope => [:clearance, :controllers, :sessions],
# :default => t('flashes.failure_after_create', :sign_up_path => sign_up_path).html_safe)
end
end
I believe this will work:
get '/sign_in' => 'sessions#new', :as => nil
Rails 4 no longer supports overriding route names, so don't name your override. The mapping is still the same so sign_in_path should still work.

URLs in mailer view files using namespaces and custom member actions

I am running Ruby on Rails 3 and I would like to use URLs in mailer view files with namespaces and custom member actions. I read this but I have still problems on implementing that.
In routes.rb I have:
namespace "users" do
resources :accounts do
member do
get 'my_action_name'
post 'my_action_name'
end
end
end
In users_mailer.rb I have:
class Users::Accounts < ActionMailer::Base
default_url_options[:host] = "test_name_site.com"
def account_delete(account)
#account = account
#action_url = users_account_url(:controller => "users/accounts", :action => "my_action_name")
...
end
end
When in the controller I try to do this:
#account = Users::Account.find(params[:id])
Users::Accounts.account_delete(Users::Account.find_by_id(#account.id)).deliver
I get this error:
ActionController::RoutingError (No route matches {:action=>"my_action_name", :controller=>"users/accounts"})
How I can solve that?
In users_mailer.rb I tryed also
# the difference is: from 'users_account_url' to 'users_accounts_url'
#action_url = users_accounts_url(:controller => "users/account_authentications", :action => "confirm_account_authentication_delete")
# the difference is: from 'users_account_url' to 'url_for'
#action_url = url_for(:controller => "users/account_authentications", :action => "confirm_account_authentication_delete")
but it doesn't work.
You are not specify an ID of a record in users_account_url
try this
#action_url = my_action_name_users_account_url(account)
http://0.0.0.0:3000/users/accounts/1/my_action_name
Routing gude

Resources