I have a form (using simple_form) which I want to implement support for translated error messages. All my translations appear with the exception of the error message.
My Customer model is:
class Customer < ActiveRecord::Base
attr_accessible :name, :phone, :email, :contact_method
validates_presence_of :phone, :email, :contact_method, :message => I18n.t(:required)
end
My fr.yml file
fr:
name: 'Nom'
phone: 'Téléphone'
email: 'Courriel'
contact_method: 'Méthode de contact'
required: 'Requis'
My form is as follows:
= simple_form_for #customer do |f|
= f.input :name, label: t(:name)
= f.input :phone, label: t(:phone)
= f.input :email, label: t(:email)
Is there something I'm missing?
At first, you should use a Symbol with validates_presence_of. Don't translate it with I18n manually:
validates_presence_of :phone, :email, :contact_method, :message => :required
Secondly, add translation for your error message to your locale file like this:
activerecord:
errors:
models:
customer:
required: 'Requis'
Related
I am working on rails 5 app. The issue I am facing is I am defining a drop down to select the user from another table in blogs form.The associations are as below.
blog.rb
has_many :blogs
def set_full_name
self.full_name = [first_name, last_name].join(' ')
end
user.rb
belongs_to :user
The problem is in this select form instead of displaying just the first_name in the drop-down list, I was to show the full_name of the user which I have defined in the user model. How can I do that?
<%= form.collection_select :user_id, User.all, :id, :first_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>
You're calling :first_name for the text property. Use :full_name
<%= form.collection_select :user_id, User.all, :id, :full_name, {prompt: "Select"}, autofocus:true, class: "form-control", id: "user" %>
Models associations are
document.rb
has_many :sections
accepts_nested_attributes_for :sections, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
section.rb
belongs_to :document
has_many :paragraphs, :dependent => :destroy
has_many :contents :through => :paragraphs
validates :user_id, :presence => { :message => "Must be filled" }
paragraph.rb
attr_accessible :user_id, :section_id, :content_id
belongs_to :section
belongs_to :content
validates :user_id, :section, :content, :presence => { :message => "Must be filled" }
paragraphs table just like a intermediate table for sections and contents and I want to save records in documents, sections and paragraphs table using single submission.
So I designed form as like
_form.html.erb
<%= form_for #document, :validate => true do |f| %>
<%= f.error_messages %>
<%= f.text_field :name %>
<% f.fields_for :sections do |builder| %>
<%= builder.text_field :name %>
<%= builder.select :content_ids .... {:multiple => true} %>
<% end %>
<% end %>
example parameters when submiting the form
{"document"=>{"name"=>"sdf", "sections_attributes"=>{"0"=>{"name"=>"sdf", "description"=>"sdf", "_destroy"=>"0", "content_ids" => ["1", "2"]}}, "commit"=>"Update Document", "id"=>"3"}
In additionally, I am updating current_user's id to user_id column of paragraphs table.
update
#document = Document.find(params[:id])
#document.attributes = params[:document]
#document.sections.each {|section|
section.user_id = current_user.id
section.paragraphs.each {|paragraph| paragraph.user_id = current_user.id}
}
if #document.save!
# success
else
render :action => 'edit'
end
I got "Validation failed: User Must be filled".
Is validation triggered when assigning attributes using object.attributes= as above
How to assign the value to user_id in paragraph object before calling save method
Might help.
<%= f.hidden_field :user_id, value: current_user.id %>
I've been getting the UnkownAttributeError for no particular reason, my models seem to be setup correctly...
School.rb
class School < ActiveRecord::Base
attr_protected :id, :created_at, :updated_at
#relationships
has_many :users
accepts_nested_attributes_for :users
end
My School model used to have the following, but it produced a MassAssignmentSecurity error for the user fields:
attr_accessible :country, :name, :state_or_province, :users_attributes
User.rb
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :instructor_id, :first_name, :last_name, :school_id
#relationships
belongs_to :school
end
new.html.haml
= simple_form_for #school do |f|
.well
= f.input :name, :as => :hidden
= f.input :country, :as => :hidden
= f.input :state_or_province, :as => :hidden
.well
= f.simple_fields_for #school.users.build do |user_form|
= user_form.input :first_name, :required => true
= user_form.input :last_name, :required => true
= user_form.input :username, :required => true
...
= f.button :submit, "Next"
Note: #school is being populated in my new action from session information gathered on the previous page, I'm making a multi-step form. The school data is perfectly valid, if I was to remove the user form it would have no trouble saving the school.
The specific error message I'm getting in my create action:
ActiveRecord::UnknownAttributeError in SchoolsController#create
unknown attribute: user
And the sent params looks a little like this:
{"school"=>{"name"=>"Elmwood Elementary", "country"=>"38",
"state_or_province"=>"448", "user"=>{"first_name"=>"joe",
"last_name"=>"asdas", "username"=>"asasdads",
"email"=>"asdasd#sdas.ca", "password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"}}, "commit"=>"Next"}
Is this maybe a bug with either Devise or simple_form? I'm using Rails 3.2.3
Ok, so apparently I needed to provide the symbol :users - the name of the relationship as my first argument for it to work.
I have a business model which has_one address and I am trying to build a form that accepts address attributes when the business is being created. I am getting error
Can't mass-assign protected attributes: address
Here are my models
Business
class Business<ActiveRecord::Base
has_one :address, :as => :addressable
attr_accessible :name, :email, :address_attributes, :password, :password_confirmation
validates_presence_of :address
validates_associated :address
accepts_nested_attributes_for :address
end
Address
class Address<ActiveRecord::Base
attr_accessible :line1, :city, :zip
validates_presence_of :line1, :city, :zip
belongs_to :addressable, polymorphic: true
end
View
%h2 Sign up
= form_for(:business, :url => business_registration_path) do |f|
= devise_error_messages!
%div
= f.label :name
%br/
= f.text_field :name
%div
= f.label :email
%br/
= f.email_field :email
%div
= f.label :password
%br/
= f.password_field :password
%div
= f.label :password_confirmation
%br/
= f.password_field :password_confirmation
%div
=f.fields_for :address do |address|
=render :partial => 'businesses/shared/address', :locals => {:f => address}
%div= f.submit "Sign up"
= render :partial => "devise/shared/links"
Partial view
%div
= f.label :line1, 'Address 1'
%br/
=f.text_field :line1
%div
= f.label :city
%br/
= f.text_field :city
%div
= f.label :zip, 'Postal Code'
%br/
= f.text_field :zip
Raw POST Data THIS IS WHERE I THINK THE PROBLEM IS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/h17NgMDr4VCTDd+FxGlAI4RWmfAat9guU9q00hYIA4=", "business"=>{"name"=>"hello", "email"=>"hello#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "address"=>{"line1"=>"this is line1", "city"=>"Andra", "country"=>"Jama", "zip"=>"123123"}}, "commit"=>"Sign up"}
shouldn't the address fields go like this
"address_attributes"=>{"line1"=>"this is line1", "city"=>"Andra", "country"=>"Jama", "zip"=>"123123"}
Why is it generating address instead of address_attributes ? This might be causing the issue. Any ideas? I have been struggling with this for about 2 hours. Appreciated any suggestions or solutions.
Upadte1:
If I make a change in the view and use
=f.fields_for :address_attributes do |address|
instead of
=f.fields_for :address do |address|
Everythings starts working but this isn't what all the tutorials and the docs are talking about ??
You should be passing an object (instance of the Business class) to form_for rather than a symbol:
= form_for(#business, :url => business_registration_path) do |f|
Presumably, you will have #business = Business.new in the controller action.
The Business class contains all the validation and association logic. Use a symbol when you want a modeless form (Rails does not infer that :business refers to the Business class, even if they share the same name).
I've created an album model and a photo model and added it to an existing rails application. I've made the photos model belong to the album model and the album model belong to an existing profile model that belongs to a user model. I don't know if I've associated them wrong and why I'm getting an error.
It's worth noting that when I go to URL/albums then everything works as it should but when I go to URL/profiles/1 (the code below is pasted in the show.html.erb file in the views/profile/ folder) then I get the error below.
This is a simple problem that I just can't solve. The four model files are below:
Album.rb:
class Album < ActiveRecord::Base
belongs_to :profile
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
end
Profile.rb:
class Profile < ActiveRecord::Base
belongs_to :user
has_many :albums
def self.get_location(profile)
location = []
location << profile.city unless profile.city.blank?
location << profile.state unless profile.state.blank?
location << profile.country unless profile.country.blank?
location << profile.postal_code unless profile.postal_code.blank?
location
end
def self.missing_fields(profile)
missing = []
if profile.first_name.blank?
missing << "first name"
end
if profile.last_name.blank?
missing << "last name"
end
if profile.job_title.blank?
missing << "job title"
end
missing
end
end
Photo.rb:
require 'paperclip'
class Photo < ActiveRecord::Base
belongs_to :album
has_attached_file :upload,
:url => "/images/:id/:style/:basename.:extension",
:path => ":rails_root/public/images/:id/:style/:basename.:extension",
:styles => {
:thumb => "75x75>",
:small => "200x200>"
}
#add in any validations you may want
end
User.rb:
class User < ActiveRecord::Base
include Gravtastic
gravtastic :size => 120
# associations
has_many :albums
has_many :photos, :through => :albums
has_many :authorizations, :dependent => :destroy
has_one :profile, :dependent => :destroy
has_many :resumes, :dependent => :destroy, :order => 'created_at DESC'
has_many :thoughts, :dependent => :destroy, :order => 'created_at DESC'
has_many :user_threads, :dependent => :destroy, :order => 'created_at ASC'
accepts_nested_attributes_for :profile
# virtual attributes
attr_accessor :first_name, :last_name
# validations
validates_presence_of :first_name
validates_presence_of :last_name
validates_length_of :username, :minimum => 4, :message => " is too short"
validates :email, :email => {:message => " is not valid"}
validates_uniqueness_of :email, :case_sensitive => false
validates_uniqueness_of :username, :case_sensitive => false
validates_length_of :password, :minimum => 4, :message => " is too short"
# authlogic
acts_as_authentic do |config|
config.crypto_provider = Authlogic::CryptoProviders::MD5
config.maintain_sessions = false
config.validate_email_field = false
config.validate_login_field = false
config.validate_password_field = false
config.login_field = :email
config.validate_login_field = false
end
def self.create_from_hash!(hash)
user = User.new(:username => Time.now.to_i, :email => '', :auth_provider => hash['provider'])
user.save(:validate => false)
if hash['provider'].downcase == 'twitter'
user.profile = Profile.create(:first_name => Twitter::Client.new.user(hash['user_info'] ['nickname'].to_s).name)
else
user.profile = Profile.create(:first_name => hash['user_info']['first_name'], :last_name => hash['user_info']['last_name'])
end
user
end
def deliver_password_reset_instructions!
reset_perishable_token!
UserMailer.deliver_password_reset_instructions(self)
end
def activate!
self.active = true
save(false)
end
def deliver_activation_instructions!
reset_perishable_token!
UserMailer.deliver_activation_instructions(self)
end
end
The profile controller has this snippet:
def show
#user = User.find_by_username(params[:id])
#profile = #user.profile
#location = Profile.get_location(#profile)
#resumes = #user.resumes
#albums = #user.albums
#photos = #user.photos
#thoughts = #user.thoughts
#shouts = UserThread.find_profile_shouts(#profile)
#shouters = UserThread.find_shouters(#shouts)
#user_thread = UserThread.new
end
The view has this:
<div id="profile_right_col">
<h2>Albums</h2>
<p>
<b>Name:</b>
<%= #albums %><br />
<% #albums.photos.each do |photo| %>
<h3><%= photo.title %></h3>
<%= image_tag photos.upload.url(:small) %>
<% end %>
</p>
<%= link_to 'Edit', edit_album_path(#albums) %> |
<%= link_to 'Back', albums_path %>
</div>
The Action Controller exception shows:
ActiveRecord::StatementInvalid in Profiles#show
Showing /Users/pawel/Ruby/Apps/cvf/app/views/profiles/show.html.erb where line #137 raised:
SQLite3::SQLException: no such column: albums.user_id: SELECT "albums".* FROM "albums" WHERE ("albums".user_id = 4)
Extracted source (around line #137):
<h2>Albums</h2>
<p>
<b>Name:</b>
<%= #albums %><br />
<% #albums.photos.each do |photo| %>
<h3><%= photo.title %></h3>
You dont have #album variable defined in your show action (you have #albums and the in the views you need to go through #albums array). So its value is nil and it doesn`t have method photos.
It worked after I added Paperclip::Railtie.insert to my application.rb.