I have a form to create a teacher, and in this form a have a table where I register the subjects that they can teach and some experience related of it.
But I dont know how to do it, in model, in controller and in view, because a have add nested fields to my teacher form, and use nested_attributes in model, and permit it in controller. but I dont know how to do it..
Model
class Tutor < User
has_many :tutor_subjects
accepts_nested_attributes_for :tutor_subjects
end
In Controller i have the functions...
def create
#tutor = Tutor.new(tutor_params)
#tutor.save
end
def tutor_params
params.require(:tutor).permit(:email,
:first_name,
:last_name,
:gender,
:password,
tutor_subjects_attributes: [])
end
end
And the view
= simple_form_for [:admin, #tutor] do |f|
= f.error_notification
.col-md-8.col-sm-12
.form-inputs
= f.input :email
= f.input :password
= f.input :first_name
= f.input :last_name
= f.input :gender, collection: {Male: 1, Female: 2}, include_blank: "--Select gender--"
%h2.well.well-sm Subjects
%table.table
%thead
%tr
%th Subject
%th Experience
%th Options
%tbody#subjects
= f.simple_fields_for :tutor_subjects_attributes do |s|
%tr.subject0
%td
= s.input :subject_id, collection: Subject.all, label: false, include_blank: "--Select subject--", input_html: { id: "tutor_subjects_attributes_0_subject_id", name: 'tutor[tutor_subjects_attributes][0][subject_id]', class: "subject" }
%td
= s.input :experience, as: :text, label: false, input_html: { placeholder: "Type your experience", name: 'tutor[tutor_subjects_attributes][0][experience]', id: "tutor_subjects_attributes_0_experience" }
%td.options
= link_to :add_subject, "#", id: "add_subject", class: "btn btn-small btn-info"
I am not sure I understand your question right but it seems like you have problems dealing with strong parameters for nested attributes.
Your tutor_params should look like
def tutor_params
params.require(:tutor).permit(
:email,
...
tutor_subjects_attributes: [
:subject_id,
:experience
]
)
end
end
Related
I am trying to create a form that updates 2 tables - commission_type and commission_tier.
I created the models, controller and form but when I submit it, my commission_tier table does not update. Only my commission_type table updates.
Can someone take a look at my code and tell me what I am doing wrong? I have combed through my code trying to find the mistake, and I cannot find it.
My models
class CommissionType < ApplicationRecord
has_many :commission_tiers
accepts_nested_attributes_for :commission_tiers
end
class CommissionTier < ApplicationRecord
belongs_to :commission_types, optional: true
end
My controller
class Admin::CommissionTypesController < Admin::BaseController
def index
#commission_types = CommissionType.all
end
def new
#commission_type = CommissionType.new
#commission_type.commission_tiers.build
end
def create
#commission_type = CommissionType.new(commission_type_params)
if #commission_type.save
redirect_to admin_commission_types_index_path
else
render "new"
end
private
def commission_type_params
params.require(:commission_type).permit(:name, :active, :allow_mass_update, :plan,
commission_tiers_attributes: [:id, :increment_value, :rate, :commission_type_id])
end
end
My form
<%= simple_form_for #commission_type, url: admin_commission_types_index_path, wrapper: :bootstrap2, :html => { :class => 'form-horizontal' } do |f| %>
<fieldset>
<legend>Properties</legend>
<%= f.input :name, label: 'Commission Name' %>
<%= f.input :active, as: :boolean, label: 'Active?', label_html: { class: 'padding-top' } %>
<%= f.input :allow_mass_update, as: :boolean, label: 'Allow mass update?', label_html: { class: 'padding-top' } %>
<%= f.input :plan, input_html: {id: 'dropdown'},
label: 'Commission Type',
collection: [ ['Select One..', 'select'], ['Flat', 'flat'], ['Flat +', 'flat_plus' ], ['Promotional', 'promotional'], ['Straight', 'straight'], ['Waterfall', 'waterfall'], ['Sliding Scale', 'sliding_scale'] ],
selected: 'select'
%>
</fieldset>
<fieldset id="flat">
<legend>Flat Commission</legend>
<%= f.simple_fields_for :commission_tiers do |builder| %>
<%= builder.input :rate %>
<%= builder.input :increment_value %>
<% end %>
</fieldset>
My form is displaying and working
UPDATE
Some additional details
CommissionType column values = [:name, :active, :allow_mass_update, :plan]
CommissionTier column values = [:id, :increment_value, :rate, :commission_type_id]
Also, when I submit my form, here is an example of what my params are
<ActionController::Parameters {"name"=>"asdf", "active"=>"1", "allow_mass_update"=>"1", "plan"=>"flat", "commission_tiers_attributes"=><ActionController::Parameters {"0"=><ActionController::Parameters {"rate"=>"45"} permitted: true>} permitted: true>} permitted: true>
I have problem. I'm trying to get an email member from wallet_id which that relation not direct to member instead to investor account first like the sample model below.
member.rb
class Member < ActiveRecord::Base
has_one :investor_account, dependent: :destroy
end
investor_account.rb
class InvestorAccount < ActiveRecord::Base
belongs_to :member
has_many :wallets, dependent: :destroy
end
wallet.rb
class Wallet < ActiveRecord::Base
belongs_to :investor_account
end
top_up.rb
belongs_to :wallet
/top_ups/_form.html.slim
= simple_form_for [:transaction, #top_up] do |f|
.form-group
= f.input :wallet_id, collection: #wallet, input_html: { class: 'form-control' }, include_blank: "Select..."
.form-group
= f.input :amount, input_html: { min: 0, value: 0 }
/controllers/top_ups_controller.rb
def new
#top_up = TopUp.new
#wallet = Wallet.joins(:investor_account).where(investor_accounts: {approval_status: 'approved'})
end
The data on "f.input :wallet_id ...." was showed up, but it is not as email of the member instead it showing #<Wallet:0x007fd6d795e808> on all wallet dropdown, previously I also write code like below.
= f.input :wallet_id, collection: #wallet, :id, :email, input_html: { class: 'form-control' }, include_blank: "Select..."
But it throwing problem the email not found. My question was how do I pass the member on that #wallet = ... variable to get email member showing on my form? Is there better way to get that?
You can use label_method and value_method params (docs):
= f.input :wallet_id, collection: #wallet, value_method: :id, label_method: :email, input_html: { class: 'form-control' }, include_blank: "Select..."
Also if you need only id and email, there is no need to fetch all the other data from the DB, you can use pluck:
# controller
def new
#top_up = TopUp.new
#wallet = Wallet.joins(:investor_account).where(investor_accounts: {approval_status: 'approved'}).pluck(:id, :email)
end
# form
= f.input :wallet_id, collection: #wallet, value_method: :first, label_method: :last, input_html: { class: 'form-control' }, include_blank: "Select..."
I am trying to create a workout tracker. I have these nested resources
Routes.rb
resources :days do
resources :workouts
resources :meals
end
My models look fine:
Workout.rb
class Workout < ActiveRecord::Base
has_many :exercises
belongs_to :day
end
Day.rb
class Day < ActiveRecord::Base
has_many :workouts
has_many :meals
accepts_nested_attributes_for :workouts, :allow_destroy => true
accepts_nested_attributes_for :meals, :allow_destroy => true
end
The issue lies when I try to create a new workout..
../views/workouts/_form.html.haml
= form_for([#day, #workout]), html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.hidden_field :day_id, value: params[:day_id], input_html: { class: "form-control"}
= f.submit
I cant seem to save the :day_id the workout is associated with the workout though using strong params to receive them.
WorkoutsController.rb
private
def workout_params
params.require(:workout).permit(:day_id, :name, :mood)
end
def find_day
#day = Day.find(params[:day_id])
end
Instead what gets saved is a nil for :day_id
Rails Console:
Workout id: 11, name: "Hey", mood: "no", day_id: nil, created_at: "2014-12-19 14:53:29", updated_at: "2014-12-19 14:53:29"
HELP?
PS - i tried to do
= form_for([#day, #workout]), as: :foo, html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.hidden_field :day_id, value: params[:day_id], input_html: { class: "form-control"}
= f.submit
and then
def workout_params
params.require(:foo).permit(:day_id, :name, :mood)
end
But it just kept saying the :foo params where empty
The way your routes are set up, I am assuming that the day_id is being passed as a url params:
/days/:day_id/workouts
If that is the case, then you do not need to worry about #day in the form, nor the day_id in the workout_params
Form:
= form_for #workout, html: {class: 'form-horizontal'}) do |f|
= f.input :workout, label: "What did you work out", input_html: { class: "form-control"}
= f.input :mood, label: "How do you feel", input_html: { class: "form-control"}
= f.submit
Controller:
def create
#workout = #day.workouts.new(workout_params)
....
end
private
def workout_params
params.require(:workout).permit(:name, :mood)
end
def find_day
#day = Day.find(params[:day_id])
end
I have searched on stack overflow and google to no avail.
I have a person who has_one next_of_kin
I can create a person with a nested form (with cocoon) and it saves perfectly. For some reason when I then go to the edit page it deletes the associated next_of_kin record. It renders the fields populated with the record's data, but the actual record in the database gets deleted.
My form
.full-width-row
= simple_form_for #person, url: {action: action}, wrapper: 'two_column_form' do |f|
.columns.medium-4
h4 = heading
.columns.medium-8
= f.button :submit, 'Save', class: 'right button tiny radius'
.columns.medium-12
.row
.medium-8.columns
= f.input :first_name
= f.input :last_name
= f.input :email
br
h6 Next of Kin
br
= f.simple_fields_for :next_of_kin do |nok|
= render 'next_of_kin_fields', f: nok
.link
= link_to_add_association "Add Next of Kin", f, :next_of_kin, class: 'button secondary tiny next_of_kin_button'
hr
My _next_of_kin_fields partial
.nested-fields
= f.input :first_name
= f.input :last_name
= f.input :relationship, as: :select, collection: NextOfKin::RELATIONSHIP
= f.input :telephone
= link_to_remove_association "Remove next of kin", f, class: 'remove-association button tiny alert'
My Person model:
class Person < ActiveRecord::Base
has_one :next_of_kin, dependent: :destroy
accepts_nested_attributes_for :next_of_kin, allow_destroy: true
end
My Next_of_kin model:
class NextOfKin < ActiveRecord::Base
belongs_to :person
RELATIONSHIP = [ "Mother", "Father", "Brother", "Sister", "Aunt", "Uncle", "Spouse", "Other"]
end
How do I stop it from deleting the next_of_kin record when I visit the edit page?
set force_non_association_create in link_to_add_association to true to avoid this
= link_to_add_association "Add Next of Kin", f, :next_of_kin, force_non_association_create: true, class: 'button secondary tiny next_of_kin_button'
Cocoon's documentation for this parameter: https://github.com/nathanvda/cocoon#force_non_association_create
in my app I have form that looks like this
= simple_form_for #user do |f|
= f.input :name, error: false
= f.input :surname, error: false
Is there any way to avoid this repetitions (error: false)?
If they're all of the same type, something like this should work:
= simple_form_for #user do |f|
- [ :name , :surname ].each do |field|
= f.input field, error: false
If not, you could use a hash or something, instead of an array, and specify the type, as well.
It appears that simple form has the following option:
If you want to pass the same options to all inputs in the form (for
example, a default class), you can use the :defaults option in
simple_form_for. Specific options in input call will overwrite the
defaults:
<%= simple_form_for #user, defaults: { input_html: { class: 'default_class' } } do |f| %>
<%= f.input :username, input_html: { class: 'special' } %>
<%= f.input :password, input_html: { maxlength: 20 } %>
<%= f.input :remember_me, input_html: { value: '1' } %>
<%= f.button :submit %>
<% end %>
From https://github.com/plataformatec/simple_form
So, in your case:
= simple_form_for #user , defaults: { error: false } do |f|
= f.input :name
= f.input :surname
You could loop through an array of symbols
simple_form_for #user do |f|
[:name, :surname].each do |element|
f.input element, error: false
end
end