This question already has answers here:
Adding a string in front of a parameter for a form
(2 answers)
Closed 8 years ago.
I can't seem to figure this out or find a solution to this anywhere...which is crazy to me since i feel like its pretty common and simple
I want to add a little message that my client will see when the user sends them a request through the form and then it goes to an external API where they can see created tickets.
so right now my client sees
John Doe
but i want them to see
Web inquiry from John Doe
So i need to send the "Web inquiry from" part through the form
i've tried to interpolate it in the form
= f.text_field "Web inquiry from #{:subject}"
that didnt work
i've tried to add a value (not the way i want to go but i tried it anyway)
= f.text_field :subject, value: "Web inquiry from #{f.object.subject}"
that did not work either
i've tried to place it in the model
def post_tickets(params)
client.subject = "Hello from, " + client.subject
end
I'm new to rails so if you could be specific as possible that would be helpful...please dont say just do it in the controller.....thank you in advanced
here is my form
= form_for(:contacts, url: contacts_path) do |f|
= f.error_messages
= f.label :subject, "Name"
%span{style: 'color: red'} *
= f.text_field :subject, class: "text_field width_100_percent"
%br
%br
= f.label "Email"
%span{style: 'color: red'} *
%br
= f.email_field :email, class: "text_field width_100_percent"
%br
%br
= f.label "Question(s), and/or feedback"
%span{style: 'color: red'} *
%br
= f.text_area :description, class: "text_field width_100_percent", style: 'height: 100px;'
%br
%br
= f.submit "Submit", class: 'btn btn-warning'
here is my controller
class Website::ContactsController < Website::WebsiteApplicationController
def new
#contacts = Form.new
end
def create
#contacts = Form.new(params[:contacts])
#contacts.post_tickets(params[:contacts])
if #contacts.valid?
flash[:success] = "Message sent! Thank you for conacting us."
redirect_to new_contact_path
else
flash[:alert] = "Please fill in the required fields"
render action: 'new'
end
end
end
here is my model
class Form
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Translation
extend ActiveModel::Naming
attr_accessor :config, :client, :subject, :email, :custom_field_phone_number_28445,
:custom_field_name_28445, :custom_field_company_28445, :description,
:custom_field
validates_presence_of :subject, :message => '^Please enter your name'
validates_presence_of :description, :message => '^Question(s), and/or feedback can not be blank'
validates :email, presence: true
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
def initialize(attributes = {})
attributes.each do |name, value|
#attributes = attributes
end
self.config = YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new(config[:url], config[:api_key], config[:password])
end
def read_attribute_for_validation(key)
#attributes[key]
end
def post_tickets(params)
client.post_tickets(params)
end
def persisted?
false
end
end
def post_tickets(params)
# prepend to the params['subject'] just before posting
client.post_tickets "Web enquiry from #{params['subject']}"
end
Related
so I have looked at other instances of this error in other questions on SO and none seem to be helpful. So, my authentication system should allow a Business to sign up, and allow a user to sign up under their business. However, I'm getting a "couldn't find business without ID" error.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.references :company, foreign_key: true
t.timestamps
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.string :remember_digest
t.string :role
end
class CustomersController < ApplicationController
def new
set_business
#customer = #business.customers.create(user_params)
end
def create
#customer = Customer.new(customer_params)
#customer.save!
session[:customer_id] = #customer.id
redirect_to '/'
rescue ActiveRecord::RecordInvalid => ex
render action: 'new', alert: ex.message
end
private
def customer_params
params.require(:customer).permit(:first_name, :last_name, :business_no, :email, :password_digest, :business_id)
end
def set_business
#business = Business.find (params[:business_id])
end
HTML snippet: Customer.new.html.erb
<h1>Sign Up</h1>
<%= form_for(#customer) do |f| %>
<%= f.label :first_name %>
<%= f.text_field :first_name, :placeholder => "First name" %>
<%= f.label :last_name %>
<%= f.text_field :last_name, :placeholder => "Last name" %>
<%= f.label :email %>
<%= f.email_field :email, :placeholder => "Email" %>
<%= f.label :company_id %>
<%= f.collection_select :business_id, Business.all, :id, :name %>
<%= f.password_field :password_digest, :placeholder => "Password" %>
<%= f.submit "Create Account", class: "btn-submit" %>
<% end %>
class Business < ActiveRecord::Base
has_many :customers
end
class Customer < ActiveRecord::Base
belongs_to :business
end
How am I supposed to define the #business variable without getting this error so that a user can sign up under their business? I want them to select from a list of available companies on the form, which will then link them in the database when the user signs up. What am I doing wrong? I am very new to Ruby and I may need some good explanation to why this is happening.
thank you for your time :)
You should take a look at the contents of the params[], since there's no plain :business_id key, it's nested in a :customers hash:
change your set_business to somethink like this:
def set_business
#business = Business.find (params[:customer][:business_id])
end
EDIT: This will not work, since the first call to new method, the params is not supplied. You should only get a list of businesses to populate the form!
def new
#customer = Customer.new
#businesses = Business.all
end
EDIT2: In create method you don't need to set the business either, since it's already set by the form!
def create
#customer = Customer.create(customer_params)
#customer.save
end
Update the controller
customers_controller.rb
class CustomersController < ApplicationController
before_action :set_business
def new
#customer = #business.customers.build
end
def create
begin
#customer = #business.customers.new(customer_params)
#customer.save!
session[:customer_id] = #customer.id
redirect_to '/'
rescue ActiveRecord::RecordInvalid => ex
render action: 'new', alert: ex.message
end
end
private
def customer_params
params.require(:customer).permit(:first_name, :last_name, :business_no, :email, :password_digest, :business_id)
end
def set_business
#business = Business.find (params[:business_id])
end
end
I'm trying to build a contact form in Rails without storing the mails in my database. But I'm getting an undefined method 'name' for nil:NilClass error when I send the form.
My MessagesController
def create
#message = Message.new(message_params)
if #message.valid?
# TODO send message here
Messages.new_messages_email(#mailer).deliver
redirect_to root_url, notice: "Message sent! Thank you for contacting us."
else
redirect_to root_url, notice: "Something went wrong, try again!"
end
end
private
def message_params
params.require(:message).permit(
:name,
:message,
:email
)
end
My Messages model
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :message
validates_presence_of :name
validates :email, :email_format => {:message => 'is not looking good'}
validates_length_of :message, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
The email body
!!!
%html
%body
%p
= #mailer.name
Schreef het volgende:
%p= #mailer.message
%p= #mailer.email
And in my routes I have
resources :messages
I forgot to post my Messages mailer
class Messages < ActionMailer::Base
default from: "info#domein.nl"
def new_messages_email(mailer)
#mailer = mailer
mail(to: 'peter#no-illusions.nl',
subject: 'Iemand wilt contact met U')
end
end
For completion my form,
= form_for #message do |f|
.field
%br/
= f.text_field :name, :placeholder => "Naam"
.field
%br/
= f.text_field :email, :placeholder => "Emailadres"
.field
%br/
= f.text_area :message, :rows => 5, :placeholder => "Uw bericht"
.actions= f.submit "Verstuur bericht", :id => "submit"
In my MessagesController I define the paramaters for the create function, but there's something I'm doing wrong, forgetting or overlooking which causes the error.
In your controller should be probably:
Messages.new_messages_email(#message).deliver # not #mailer
Besides that, you have to reinitialize #message within your mailer, e.g:
class Messages < ActionMailer::Base
def new_messages_email(msg)
#message = msg
end
end
I am having a little trouble with a form in Rails. (I'm new to Rails)
What I get after submitting the form is this:
--- !ruby/hash:ActionController::Parameters
utf8: "✓"
name: Jim
email: Jim#jim.com
subject: hello
message: goodbye
controller: contacts
action: create
It should be like this:
contact:
name: Jim
email: Jim#jim.com
subject: hello
message: goodbye
I have no idea what I'm doing wrong here. Here is the form (minus all the bootstrap divs and spans):
views/contacts/new.html.erb
<%= form_for(#contact, url: contact_path) do |f| %>
<%= f.text_field :name, name: "name", value: nil, class: 'form-control', placeholder: 'Enter full name' %>
<%= f.email_field :email, name: "email", class: 'form-control', placeholder: 'Enter email address' %>
<%= f.text_field :subject, name: "subject", class: 'form-control',
placeholder: 'Enter subject' %>
<%= f.text_area :message, name:"message", class: 'form-control', rows: 6, placeholder: 'Enter your message for us here.' %>
<%= f.submit :submit, class: 'btn btn-default pull-right' %>
<% end %>
config/routes.rb
get 'contact' => 'contacts#new'
post 'contact' => 'contacts#create'
controllers/contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(params[:contact]) #<-- always fails because no :contact
if #contact.valid?
if #contact.send_mail
# todo
else
# todo
end
else
flash.now[:error] = params.inspect
render 'new'
end
end
end
models/contact.rb
class Contact
include ActiveAttr::Model
attribute :name
attribute :email
attribute :subject
attribute :message
validates_presence_of :name
validates_format_of :email, with: /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
validates_presence_of :subject
validates_presence_of :message
def send_mail
ContactMailer.form_message(self).deliver_now
end
end
I have tried using form_for(:contact), routing with resources, changing the model to use the mail_form gem, but still no luck. Of course I could just get all values by doing params[:name] etc. but it bugs me that isn't creating a single hash with all form input values. Does anyone know why this is happening? Thanks in advance.
Remove the name: '...' option, because the helpers already set the name and it's not the one you are setting. In your case, rails will expect that the fields are named like contact[name] and contact[email] instead of the ones you are setting.
I'm relatively new to Rails (using Rails 4), and am having a problem with validation for my user model. Even when the form is fully filled in with both the passwords, when I submit the code two errors print out:
{:password=>["can't be blank"], :password_confirmation=>["doesn't match Password"]}
I would like the user to be saved into the database, but these validation errors are preventing that from happening. What I would like to know is what I need to change in order to get rid of these errors.
I am printing out the params object and it looks like this (the authenticity token is omitted here):
params: {"utf8"=>"✓","authenticity_token"=>"[omitted]",
"user"=>{"username"=>"testuser1", "password"=>"test",
"password_confirmation"=>"test", "email_attributes"=>{"email"=>"d#d.com"},
"first_name"=>"test", "last_name"=>"user", "gender"=>"male", "city"=>"la",
"state"=>"ca", "country"=>"usa", "dob"=>"1980-11-20"},
"commit"=>"Create Account", "action"=>"create", "controller"=>"users"}
So it appears that the password and password_confirmation attributes are getting passed correctly. I am wondering if this may have to do with the virtual attribute password I have defined in the user model, but if that is the case I am still not quite sure how to solve this problem. Any help would be greatly appreciated. Let me know if I need to elaborate further.
Here is relevant code for reference:
Controller:
class UsersController < ApplicationController
def new
#user = User.new
#user.build_email
end
def create
if #user = User.create(user_params)
logger.debug "#{#user.errors.messages}"
logger.debug "params: #{params}"
redirect_to :action => "new"
else
logger.debug "#{#user.errors.messages}"
logger.flush
redirect_to :action => "new"
end
end
private
def user_params
params.require(:user).permit(:username, :password, :password_confirmation, :first_name, :last_name, :gender, :dob, :city, :state, :country, :admin_level, email_attributes: [:email])
end
end
Model:
class User < ActiveRecord::Base
has_one :email
validates_presence_of :username, :email, :password
validates_confirmation_of :password, :on => :create
accepts_nested_attributes_for :email
def password_valid?(candidatePass)
candidatePassAndSalt = "#{candidatePass}#{self.salt}"
candidatePasswordDigest = Digest::SHA1.hexdigest(candidatePassAndSalt)
if (candidatePasswordDigest == self.password_digest)
return true
else
return false
end
end
def password
end
def password=(text)
self.salt = Random.new.rand
passAndSalt = "#{text}#{self.salt}"
self.password_digest = Digest::SHA1.hexdigest(passAndSalt)
end
end
View:
<%= form_for #user, url: {action: "create"}, html: {class: "user-creation-form"} do |f| %>
<%= f.text_field :username %>username<br/>
<%= f.password_field :password %>pw<br/>
<%= f.password_field :password_confirmation %>pwcopy<br/>
<%= f.fields_for :email do |email_form| %>
<%= email_form.text_field :email %>email<br />
<% end %>
<%= f.text_field :first_name %>first<br/>
<%= f.text_field :last_name %>last<br/>
<%= f.radio_button :gender, "male" %>
<%= f.label :gender_male, "M" %>
<%= f.radio_button :gender, "female" %>
<%= f.label :gender_female, "F" %><br />
<%= f.text_field :city %>city<br/>
<%= f.text_field :state %>state<br/>
<%= f.text_field :country %>country<br/>
<%= f.date_field :dob %>dob<br/>
<%= f.submit "Create Account" %><br/>
<% end %>
The issue is your empty getter:
def password
end
It always return nil.
2 small additions to the previous answer, which should resolve your issue by the way.
1) If you're using Rails >3 (I assume you are by looking at your user_params method in the controller) you don't have to specify all those password fields and validations.
ActiveRecord automatically includes this ActiveModel method :
has_secure_password
More details at : http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password
2) If the uncrypted password/password_confirmation are shown in your log files your app is insecure. Add this to your config/application.rb :
config.filter_parameters = [:password, :password_confirmation]
This should not be needed if you are using has_secure_password in your User model.
I am working with polymorphic associations and having some trouble. My models are setup like so:
class User < ActiveRecord::Base
has_one :phone, :as => :callable, :dependent => :destroy
end
class Client < ActiveRecord::Base
has_one :phone, :as => :callable, :dependent => :destroy
end
class Phone < ActiveRecord::Base
belongs_to :callable, :polymorphic => true
end
In my Users Controller
def create
#user = User.new(params[:user])
if #user.save
#user.phone.create(:area_code => params[:user][:area_code], :phone => params[:user][:phone])
redirect_to #user, :notice => "Account created successfully!"
else
render 'new'
end
end
In the development log I see where the phone and user are being inserted correctly, but when I go to edit the user, the fields for phone in the form are blank. Here is my edit method:
def edit_employee
#user = User.find(params[:id])
#title = "Edit #{#user.name}"
end
My edit user form looks like this.
- form_for #user do |f|
- if #user.errors.any?
.error_messages
%h2 Please correct the following errors
%ul
- for message in #user.errors.full_messages
%li= message
%p
= f.label :name, "Name"
= f.text_field :name
%p
= f.label :email, "Email Address"
= f.text_field :email
%p
= f.label :phone, "Phone"
= f.text_field :area_code, :style => "width: 50px;"
= f.text_field :phone, :style => "width: 100px;"
= f.label :ext, "Ext."
= f.text_field :extension, :style => "width: 60px;"
%p
= f.label :password, "Password"
= f.password_field :password
%p
= f.label :password_confirmation, "Confirm Password"
= f.password_field :password_confirmation
%p.button= f.submit
I know I should be adding something to this edit method, perhaps
#phone = #user.phone
But that didn't work either. This is the first go round with polymorphic associations so any help and and pointers are much appreciated. I watched the Railscasts on this topic but it didn't seem to follow my underlying functionality. Once again, thanks in advance for any help and let me know if any more information is needed!
you should look into using fields_for and nested_attributes. http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Do you have attr_accessible set in the user.rb model? If not I would add it because that is a security issue.
Ok I added the
accepts_nested_attributes_for :phone
in the user model. I also added the fields for phone in the new user form like so
%p
- fields_for #user.phone do |phone|
= phone.label :phone, "Phone"
= phone.text_field :area_code, :style => "width: 50px;"
= phone.text_field :phone, :style => "width: 100px;"
= phone.label :ext, "Ext."
= phone.text_field :extension, :style => "width: 60px;"
but now I am getting the ActionView::Template::Error (undefined method `model_name' for NilClass:Class) exception.
And yes I have attr_accessible in my model. I just placed a very watered down version in here.