I am trying to create a book consultation form with following fields from two models
User Model
- first_name
- last_name
- email
- contact_number
Message Model
:message_text
The desired form rendered should be presenting the user all the User Model fields along with a text area which would be :message_text for the Message Model.
The code of User Model is
class User < ActiveRecord::Base
has_many :messages
validates :first_name , presence: true
validates :last_name , presence: true
validates :email, presence: true
validates :contact_number,presence: true
accepts_nested_attributes_for :messages
end
The Code of Message Model
class Message < ActiveRecord::Base
validates :message_text, presence: true
belongs_to :user , :class_name => 'User', :foreign_key => 'id'
end
The index controller of User which renders the form looks like
def index
#users = User.all
#user = User.new
#user.messages.build
end
The view file looks like
<%= form_for(#user) do |f| %>
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field :first_name %>
</div>
<div class="form-group">
<%= f.label :last_name %>
<%= f.text_field :last_name %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="form-group">
<%= f.label :contact_number %>
<%= f.text_field :contact_number %>
</div>
<div class="form-group">
**the fields_for does not get rendered at all into the HTML**
<%= f.fields_for :messages do |ff| %>
<%= ff.label :message_text %>
<%= ff.text_field :message_text %>
<% end %>
</div>
<div class="btn primary-btn">
<%= f.submit 'Book Free Consultation'%>
</div>
All other fields get rendered. Can anybody please help me in spotting the mistake . Thank you in advance
your migration file should be like below
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :contact_number
end
end
end
class CreateMessages < ActiveRecord::Migration
def change
create_table(:messages) do |t|
t.string :message_text
t.references :user, index: true
end
end
end
Related
So I have a form and corresponding classes. I got an error:
undefined method `start' for #<Klass id: nil, name: nil, teacher: nil, day: nil>
for line: <%= f.text_field :start, class: 'form-control' %>
and (when I'm trying to delete the above one) <%= f.text_field :duration, class: 'form-control' %>
removing both fields makes my website ok.
My whole form code:
<%= form_for #klass do | f | %>
<div class = “form-group”>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :teacher %>
<%= f.text_field :teacher, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :start %>
<%= f.text_field :start, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :duration %>
<%= f.text_field :duration, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :day %>
<%= f.select :day, ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] %>
</div>
<%= f.submit 'Submit', class: 'btn btn-default' %>
</div>
<% end %>
model (changing integer to string doesn't make any difference, but that is the only difference betweenthese two fields and the rest of the form that I can see) :
class Klass < ActiveRecord::Base
validates :name, presence: true
validates :teacher, presence: true
validates :day, presence: true
validates :start, presence: true
validates :duration, presence: true, numericality: { only_integer: true }
end
database file:
class CreateKlasses < ActiveRecord::Migration[5.0]
def change
create_table :klasses do |t|
t.string :name
t.string :teacher
t.string :day
t.integer :start
t.integer :duration
end
end
end
and controller:
class KlassesController < ApplicationController
def new
#klass = Klass.new
end
end
Looks for me like I missed to declare these two form fields but where else I can look for it?
1- rake db:rollback
make sure you have these fields added in migration file
class CreateKlasses < ActiveRecord::Migration[5.0]
def change
create_table :klasses do |t|
t.string :name
t.string :teacher
t.string :day
t.integer :start
t.integer :duration
end
end
end
2- rake db:migrate
now reload rails console
reload!
or just close rails console and open rails console again.
check again Klass.new if it has all field that you added in migration. if those field exists then restart server and thats it.
I have polymorphic associations with different models that I want to save upon submitting the registration form using devise. i.e:
User
Company + ContactInfo
Employee + ContactInfo
I understand that nesting forms is not recommended but What would be the best way to achieve this?
Thanks
models:
class User < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company
end
class Company < ActiveRecord::Base
has_many :employees
has_one :contact_info, as: :contactable
accepts_nested_attributes_for :contact_info
end
class Employee < ActiveRecord::Base
belongs_to :company
has_one :contact_info, as: :contactable
accepts_nested_attributes_for :contact_info
end
class ContactInfo < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
migrations:
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name
t.references :contact_info, index: true
t.string :website
t.timestamps null: false
end
add_foreign_key :companies, :contact_infos
end
end
class CreateEmployees < ActiveRecord::Migration
def change
create_table :employees do |t|
t.string :first_name
t.string :last_name
t.references :company, index: true
t.references :contact_info, index: true
t.string :job_title
t.timestamps null: false
end
add_foreign_key :employees, :contact_infos
end
end
class CreateContactInfos < ActiveRecord::Migration
def change
create_table :contact_infos do |t|
t.string :email
t.string :phone
t.string :mobile
t.string :contactable_type
t.integer :contactable_id
t.timestamps null: false
end
end
end
registration controller:
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up).push(:name, :email, :password, company_attributes: [ :id, :name, :website, :company_type, :number_of_employees, contact_info_attributes: [ :id, :email, :phone, :mobile]])
end
devise's new registration:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :role => 'form'}) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<% resource.build_company %>
<%= f.fields_for :company do |f| %>
<%= render "companies/fields", f: f %>
<% end %>
<% resource.company.build_contact_info %>
<%= f.fields_for :contact_info do |f| %>
<%= render "contact_infos/fields", f: f %>
<% end %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, :autofocus => true, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
</div>
<%= f.submit 'Sign up', :class => 'button right' %>
<% end %>
Console:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Nb6Na8P93s1dYvlDIQuiG11IoDeSzSylH4BCN8Tm7ipxCsbsdiWjDx5tJpijwldkjK4pPfjuwROnEvybYS7UIQ==", "plan"=>"free", "user"=>{"company_attributes"=>{"name"=>"Company Name", "website"=>"company website", "company_type"=>"company type", "number_of_employees"=>"121"}, "contact_info"=>{"email"=>"company#email.com", "phone"=>"1234", "mobile"=>"1234"}, "name"=>"user_name", "email"=>"user_email#email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameter: contact_info
only User and company params are saving well. I was trying to get the devise_parameter_sanitizer to work with nesting contact_info in company first without trying the same with employee just yet, any idea what I'm doing wrong or any tips if im on the right track?
Thanks!
Update:
However contact_info params are permitted if I nest the contact_info form fields within the company form fields like so:
<% resource.build_company %>
<%= f.fields_for :company do |f| %>
<%= render "companies/fields", f: f %>
<% resource.company.build_contact_info %>
<%= f.fields_for :contact_info do |cf| %>
<%= render "contact_infos/fields", f: cf %>
<% end %>
<% end %>
the question is, is that good practice?
This is a guess - but your contact_info for the company isn't nested inside the company section. Try something like this (note, not tested, probably buggy)
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :role => 'form'}) do |f| %>
<%= devise_error_messages! %>
<%= hidden_field_tag 'plan', params[:plan] %>
<% resource.build_company %>
<%= f.fields_for :company do |f| %>
<%= render "companies/fields", f: f %>
<%# this is now nested inside the company-fields %>
<% resource.company.build_contact_info %>
<%= f.fields_for :contact_info do |f| %>
<%= render "contact_infos/fields", f: f %>
<% end %>
<% end %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, :autofocus => true, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
</div>
<%= f.submit 'Sign up', :class => 'button right' %>
HI I am trying to implement the MTI in my application. I have a Person Model and 2 models inheriting from it: Client and TeamMember. When creating a Team Member I want to save to to database vallues for both person (first and last name, email etc) and team member(experience level, type of team, if lead or not). I am using the nested attributes form so in my team member form I am nesting the person fields. Unfortunatellly I am getting "Can't mass-assign protected attributes: person" error when trying to save. Can anyone tell me how this can be solved? Thanks!
Models:
UPDATED TeamMember class but still the same error
also tried people_attributes and persons_attributes and none of these worked
class TeamMember < ActiveRecord::Base
has_many :project_team_members
has_many :projects, through: :project_team_members
has_one :person, as: :profile, dependent: :destroy
accepts_nested_attributes_for :person
attr_accessible :person_attributes, :experience_level, :lead, :qualification, :team
end
class Person < ActiveRecord::Base
belongs_to :company
belongs_to :profile, polymorphic: true
attr_accessible :email, :first_name, :last_name, :phone_number, :profile_id, :profile_type
end
Controller as follows:
class TeamMembersController < ApplicationController
def create
person = Person.create! { |p| p.profile = TeamMember.create!(params[:team_member]) }
redirect_to root_url
end
and the view:
<%= form_for(#team_member) do |f| %>
<%= f.fields_for :person do |ff| %>
<div>
<%= ff.label :first_name %>
<%= ff.text_field :first_name %>
</div>
<div>
<%= ff.label :last_name %>
<%= ff.text_field :last_name %>
</div>
<div>
<%= ff.label :phone_number %>
<%= ff.text_field :phone_number %>
</div>
<div>
<%= ff.label :email %>
<%= ff.text_field :email %>
</div>
<div>
<%= ff.label :company_id %>
<%= ff.text_field :company_id %>
</div>
<% end %>
<div class="field">
<%= f.label :team %><br />
<%= f.text_field :team %>
</div>
<div class="field">
<%= f.label :experience_level %><br />
<%= f.text_field :experience_level %>
</div>
<div class="field">
<%= f.label :qualification %><br />
<%= f.text_field :qualification %>
</div>
<div class="field">
<%= f.label :lead %><br />
<%= f.check_box :lead %>
</div>
<div class="actions">
<%= f.submit %>
</div>
UPDATED TeamMembersController (Solution thanks to the courtesy of Tiago)
def new
#team_member = TeamMember.new
#team_member.build_person
respond_to do |format|
format.html # new.html.erb
format.json { render json: #team_member }
end
end
def create
#team_member = TeamMember.create!(params[:team_member])
redirect_to root_url
end
To mass assign attributes in a nested form, you'll need to specify:
class TeamMember < ActiveRecord::Base
has_many :project_team_members
has_many :projects, through: :project_team_members
has_one :person, as: :profile, dependent: :destroy
:experience_level, :lead, :qualification, :team #what is this line doing??
accepts_nested_attributes_for :person
attr_accessible :person_attributes
end
EDIT:
In the action called before the form you need to build person. Like:
#team_member = TeamMember.new
#team_member.build_person
Then you'll have one person (non-persisted) associated with #team_member.
I have a form from user
<%= form_for(#user) do |f| %>
<%= f.fields_for :businesses do |field| %>
<div class="field">
<%= field.label :address %>
<%= field.text_field :address %>
</div>
<div class="field">
<%= field.label :city %>
<%= field.text_field :city %>
</div>
<% end %>
<% end %>
It does not display my fields, but when i change businesses to business, then it shows, or if I remove the f from f.fields_for. But I don't think it properly saves into database.
my user model
class User < ActiveRecord::Base
has_many :businesses
accepts_nested_attributes_for :businesses
en
my business model
class Business < ActiveRecord::Base
attr_accessible :user_id, :address, :city
belongs_to :user
end
my bussiness migration
class CreateBusinesses < ActiveRecord::Migration
def change
create_table :businesses do |t|
t.integer :user_id
t.string :address
t.string :city
t.timestamps
end
end
end
Any suggestions as to what I'm doing wrong?
Thanks
You should build a business before it can display a form for it:
#user.businesses.build
Use that before using fields_for
Also check out this great gem for managing nested forms:
https://github.com/ryanb/nested_form
Here's my user model:
class User < ActiveRecord::Base
has_one :teacher, :dependent => :destroy
accepts_nested_attributes_for :teacher, :allow_destroy => true
attr_accessible :email, :password, :password_confirmation, :remember_me, :teacher_attributes
end
Here's my teacher model:
class Teacher < ActiveRecord::Base
belongs_to :user
attr_accessible :user_id, :first_name, :last_name
validates_presence_of :user_id, :first_name, :last_name
end
Here's my form:
<%= form_for(#user, :url => registration_path(:user)) do |user| %>
<%= user.text_field :email %>
<%= user.text_field :password %>
<%= user.text_field :password_confirmation %>
<%= user.fields_for resource.build_teacher do |t| %>
<%= t.text_field :first_name %>
<%= t.text_field :last_name %>
<%= t.text_field :phone %>
<% end %>
<%= user.submit 'Confirm' %>
<% end %>
Except that this thing won't "accept nested attributes"
My development log says:
WARNING: Can't mass-assign protected attributes: teacher
I don't know if it's related, but the form isn't generating fields inside a teacher_attributes array or anything - it's inside teacher. I'm guessing that's where my problem is, but I don't how to make it put the fields inside it. Please help.
Thanks!
Try these things:
At top of view:
<% #user.build_teacher if #user.teacher.nil? %>
For the fields for:
<%= user.fields_for :teacher do |t| %>
Also, personally, I like naming the block parameters in forms (the part |user| and |t|) as |form| (because when you're having a long day, and you see user down in the view and not form, it can confuse you!)