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>
Related
I've got an app where the user has to fill out a survey. I need to store user's answers in inside TestResult model which have only one field answers:string
With current implementation I'm getting params from the form as:
params => {
{
"question_#{id}": "some answer 1",
"question_#{id}": "some answer 12345",
}
}
Which I want to change to the below structure:
# expected hash params
params => {
{
question: 'first question',
answer: 'some answer 1'
},
{
question: 'second question',
answer: 'some answer 123431'
}
}
What should I change (probably in a view) to get this hash?
new.html.erb
<%= simple_form_for :test_results, url: test_results_path do |f| %>
<% #randomize_questions.map do |q| %>
<%= q[:question] %>
<%= f.input "question_#{q[:id]}", collection: q[:answers], as: :radio_buttons %>
<% end %>
<%= f.button :submit %>
<% end %>
controller:
class TestResultsController < ApplicationController
before_action :fetch_random_questions, only: [:new, :create]
def new
#test_result = TestResult.new
end
def create
#test_result = TestResult.new(
answer: test_result_params,
)
#test_result.save
redirect_to dummy_path
end
end
private
def test_result_params
params.require(:test_results).permit!
end
def fetch_random_questions
TestQuestion.where(published: true).order('RANDOM()')
#randomize_questions = test_questions.map do |obj|
{
id: obj.id,
question: obj.question,
answers: [obj.correct_answer, obj.other_answer1, obj.other_answer2, obj.other_answer3],
}
end
end
end
TestResult model
class TestResult < ApplicationRecord
serialize :answer, Hash
serialize :answer, String
validates :answer, presence: true
end
The params get his structure from the input names.
So you could add an hidden field for question, and then specify a name for both of your fields.
<%= simple_form_for :test_results, url: test_results_path do |f| %>
<% #randomize_questions.map do |q| %>
<%= q[:question] %>
<%= f.input "question_#{q[:id]}", as: :hidden, input_html: { name: "test_results[#{q[:id]}][question]", value: q[:question] } %>
<%= f.input "question_#{q[:id]}", collection: q[:answers], as: :radio_buttons, input_html: { name: "test_results[#{q[:id]}][answer]" } %>
<% end %>
<%= f.button :submit %>
<% end %>
Params should looks like this:
params => {
test_result: {
1 => {
question: "...",
answer: "..."
},
2 => {
question: "...",
answer: "..."
}
}
}
Not tested. Could you tell if that's works for you?
I am using Simple Form in a Rails application in which a FormsController controller was defined as follow :
class FormsController < ApplicationController
def index
#forms = Form.all
end
def new
#form = Form.new(form_params)
end
...
private
def form_params
params.require(:form).permit(:user, :name, :tag, :link, :repo)
end
end
A new view is used to get some inputs from user
<div class="form">
<%= simple_form_for #param do |f| %>
<div class="form-inputs";>
<%= f.input :user %>
<%= f.input :name %>
<%= f.input :tag %>
<%= f.input :link %>
<%= f.input :repo %>
</div>
<div class="form-actions">
<%= f.button :submit, "Create", class: "btn-primary" %>
</div>
<% end %>
</div>
I checked what's the generated name for a each field using inspect :
<input type="text" name="form[user]" id="form_user">
Printing parameters in controller while submitting a form returns :
{“user”=>”value1”, “name”=>”value2”, “tag”=>”value3”, “link”=>”value4”, “repo”=>”value5”}
From now, I would like to duplicate that's simple form few times. So, I first updated the field name from form[<parameter>] to form[1][<parameter>]
<div class="form-inputs";>
<%= f.input :user, input_html: { name: 'form[1][user]' } %>
<%= f.input :name, input_html: { name: 'form[1][name]' } %>
<%= f.input :tag, input_html: { name: 'form[1][tag]' } %>
<%= f.input :link, input_html: { name: 'form[1][link]' } %>
<%= f.input :repo, input_html: { name: 'form[1][repo]' } %>
</div>
What I get from now as parameters output is :
"form"=>{"1"=>{"“user”"=>"value1", "“name”"=>"value2", "“tag”"=>"value3", "“link”"=>"value4", "“repo”"=>"value5"}}
What's the best way to dynamically allocate the id to the form[<id>][user] to the field ?
Is it possible to get parameters formatted as follow ?
form => { 1 => {user: "user1" }, 2 => {user: "user2" }, 3 => {user: "user3" }.. }
form => { 1 => {name: "name1" }, 2 => {name: "name2" }, 3 => {name: "name3" }.. }
...
I'm using ActiveAdmin for an admin panel. In the nested form, I need to use some filtering, for example, in the dropdown I need to select an option name, and in the second dropdown should be displayed the option's values.
For this, I want to use activeadmin-ajax_filter gem. Option and OptionValue are connected with each other: Option has_many :option_values, and OptionValue belongs_to Option. I create option_values through the nested form when I create the Option.
Then, I have a Product model, in which via nested form I create a Variant. So, Variant belongs_to :option_value belongs_to :product and OptionValue has_many :variants, Product has_many :variants.
Just for now, when I want to create a new variant, I can select all the option values I have in the db. I want to select an option (for example a size), and then, in a dropdown below - select the appropriate values (XL, S, and so on).
The code for my active_admin resources is:
ActiveAdmin.register Product do
permit_params :category_id, :name, :description, :short_description, :image, :subtitle,
product_currencies_attributes: [:id, :product_id, :currency_id, :price, :_destroy],
variants_attributes: [:id, :product_id, :in_stock_id, :sold_out_id, :option_value_id, :image, :visible,
:orderable, :_destroy]
index do
column :id
column :image do |product|
image_tag(product.image.url(:thumb)) if product.image
end
column :category_id do |product|
category = Category.find(product.category_id)
link_to category.name, admin_category_path(category)
end
column :name
column :short_description
column :description do |product|
product.description.truncate(90)
end
column :subtitle
column :created_at
column :updated_at
actions
end
show do
tabs do
tab 'Product' do
attributes_table do
row :id
row :image do
image_tag(product.image.url(:medium))
end
row :category_id do
category = Category.find(product.category_id)
link_to category.name, admin_category_path(category)
end
row :name
row :short_description
row :description
row :subtitle
row :created_at
row :updated_at
end
end
tab 'Prices' do
attributes_table do
row :prices do
div do
product.product_currencies.each do |product_currency|
div do
"#{Currency.find(product_currency.currency_id).name}: #{product_currency.price}"
end
end
end
end
end
end
tab 'Variants' do
div do
'Variants will be here soon =)'
end
end
end
end
form do |f|
tabs do
tab 'Product' do
f.inputs do
f.input :category_id, as: :select, collection: Category.all.collect { |category| [category.name, category.id] }
f.input :name
f.input :short_description
f.input :description
f.input :subtitle
f.input :image, as: :file
end
end
tab 'Price' do
f.inputs do
f.has_many :product_currencies, allow_destroy: true, heading: false, new_record: 'Add New Price' do |product_currency|
product_currency.template.render partial: 'product-price-form', locals: { product_currency: product_currency,
product_id: params[:id].to_i }
end
end
end
tab 'Variants' do
f.inputs do
f.has_many :variants, allow_destroy: true, heading: false, new_record: 'Add new Variant' do |variant|
variant.template.render partial: 'variant-form', locals: { variant: variant, product_id: params[:id].to_i }
end
end
end
tab 'SEO' do
div do
'SEO inputs will be here'
end
end
end
f.actions
end
end
So, I've installed activeadmin-ajax_filter gem. I tried to follow the documentation, but as a result - nothing. As far, as I understand, I have to put this line of code to my Option activeadmin model: activeadmin-ajax_filter, and in the form use this:
f.input :option, as: :ajax_select, data: {
url: filter_admin_options_path,
search_fields: [:name],
static_ransack: { active_eq: true },
ajax_search_fields: [:option_value_id],
}
But still - nothing. By the way, the partial is:
<% if #product.new_record? %>
<% if Product.any? %>
<% new_product_id = Product.order(id: :desc).first.id + 1 %>
<% variant.input :product_id, as: :hidden, input_html: { value: new_product_id } %>
<% else %>
<% variant.input :product_id, as: :hidden, input_html: { value: 1 } %>
<% end %>
<% else %>
<% variant.input :product_id, as: :hidden, input_html: { value: product_id } %>
<% end %>
<% variant.input :in_stock_id, as: :select, collection: InStock.all.collect { |in_stock| [in_stock.name, in_stock.id] } %>
<% variant.input :sold_out_id, as: :select, collection: SoldOut.all.collect { |sold_out| [sold_out.name, sold_out.id] } %>
<%# variant.input :option, as: :ajax_select, collection: Option.all.collect { |option| [option.name, option.id] },
# data: {
# url: filter_admin_options_path,
# serarch_fields: [:name],
# static_ransack: { active_eq: true },
# ajax_search_fields: [:option_value_id]
# }
#%>
<% variant.input :option_value_id, as: :select, collection: OptionValue.all
.collect { |option_value| [option_value.value, option_value.id] } %>
<% variant.input :visible %>
<% variant.input :orderable %>
<% variant.input :image, as: :file %>
I have a model (FooBar) with three columns:
Foo -> String
Bar -> JSON
Baz -> String
I want to create a form for this model
Bar has default attributes of: {zing: {}, zaz: {}, laz: {}}
I would like to have the following inputs:
f.input :foo
f.input :zing
f.input :zaz
f.input :laz
f.input :baz
I tried to do this using fields_for and passing in each key and converting it to a symbol:
bar.each do |k,v|
f.input k.to_sym
end
but the error I'm getting is that FooBar has undefined method of :zaz
Any ideas would be appreciated, thanks.
You should be able to do it like this:
f.simple_fields_for :bar do |bar_f|
bar.each do |k,v|
bar_f.input k.to_sym
end
end
Don't forget to allow the parameters in the controller.
You can do something like this:
class User < ActiveRecord::Base
serialize :preferences, HashSerializer
store_accessor :preferences, :blog, :github, :twitter
end
And then you will have access to blog, github and twitter just as if they were normal properties in the model and your form is going to look something like this:
= simple_form_for(#user, html: { class: "form" }) do |f|
= f.input :blog
= f.input :github
= f.input :twitter
You have more info in this link! https://github.com/plataformatec/simple_form/wiki/Nested-inputs-for-key-value-hash-attributes
Hope it helps!
Set #temp variable
#temp = FooBar.new
#temp.data = {zing: "", zaz: "", laz: ""}
This code works for me
<%= simple_form_for #temp do |f| %>
<%= f.simple_fields_for :data do |data_f| %>
<% #temp.data.each do |k,v| %>
<%= data_f.input k.to_sym %>
<% end %>
<% end %>
<%= f.button :submit %>
<% end %>
Don't forget about permission params
params.require(:temp).permit(data: [:zing, :zaz, :laz])
If you don't want to define accessors, you could do something like:
= simple_form_for(#foo_bar) do |f|
= f.simple_fields_for :bar do |bf|
= bf.input :zing, input_html: { value: f.object.bar[:zing] }
= bf.input :zaz, input_html: { value: f.object.bar[:zaz] }
= bf.input :laz, input_html: { value: f.object.bar[:laz] }
You would need to initialise bar with {} in your controller
In my Rails application I have simple search functionality. I want to extract to Form Object but don't know how to do. I have search form which looks like this:
.row
= horizontal_simple_form_for :cars, {url: cars_path, method: :get} do |f|
.col-md-4
.row
.col-md-12
= f.input :handover_location, label: I18n.t('.handover'), collection: Location.all.map{|hl| [hl.location_address, hl.id]}
= f.input :return_location, label: I18n.t('.return') ,collection: Location.all.map{|rl| [rl.location_address, rl.id]}
= f.input :car_class, label: I18n.t('.car_class') ,collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
.col-md-4
= f.input :handover_date, as: :string, label: false
= f.input :return_date, as: :string, label: false
= f.submit class: 'btn btn-success'
Cars controller:
class CarsController < ApplicationController
skip_authorization_check
def index
#cars = Car.search(params)
end
def show
end
end
And class method in Car model which search correct cars:
def self.search(params)
self.joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?",
params[:cars][:return_date], params[:cars][:handover_date]).
joins(:car_class).where("car_classes.id= ?", params[:cars][:car_class])
.cars_at_both_locations(params[:cars][:handover_location], params[:cars][:return_location])
end
Now I'm trying to extract this to Form Object. I've created a file search_form.rb:
class SearchForm
include ActiveModel::Model
attr_accessor :handover_date, :return_date, :handover_location, :return_location, :car_class
end
But now I don't know how to handle my params to this form object. Thank's in advance.
I wish I could help you with the Form Object stuff, but I need to learn more about classes & modules
I can help you with the search functionality, as we've done it before here
Here's the code we used:
#View
<%= form_tag search_path, :method => :post, :id => "SearchForm" do %>
<%= text_field_tag :search, params[:search], placeholder: 'Search your favourite products or brands', :autocomplete => :off %>
<%= image_submit_tag 'nav_bar/search.png' %>
<% end %>
#config/routes.rb
match 'search(/:search)', :to => 'products#search', :as => :search, via: [:get, :post]
#app/controllers/products_controller.rb
def search
#products = Product.search(params[:search])
respond_to do |format|
format.js { render :partial => "elements/livesearch", :locals => {:search => #products, :query => params[:search]} }
format.html { render :index }
end
end
Notice the form_tag we used?
Simple form does not work with form_tag currently (it requires an object) - we just send the data with a GET request to the controller & that then sends the data to the Product model
I think your problem will be caused by the use of your SearchForm object. You only need this because your use of simple form means you have to pass an object. Problem being this is not necessary for search
A better way will be to use a standard form_tag, and send the request directly to your controller. This will allow you to process the data as params, which you'll be able to send directly to your Car model
--
I can write some code specific to you if you want
I found solution on my own.
Cars controller:
def index
#search_form = SearchForm.new(params[:search_form])
#cars = #search_form.submit(params[:search_form])
end
search_form.rb:
class SearchForm
include ActiveModel::Model
attr_accessor :handover_date, :return_date, :handover_location, :return_location, :car_class
def submit(params)
Car.search(params)
end
end
Search form in view:
.row
= horizontal_simple_form_for SearchForm.new, {url: cars_path, method: :get} do |f|
.col-md-4
.row
.col-md-12
= f.input :handover_location, label: I18n.t('.handover'), collection: Location.all.map{|hl| [hl.name, hl.id]}
= f.input :return_location, label: I18n.t('.return') ,collection: Location.all.map{|rl| [rl.name, rl.id]}
= f.input :car_class, label: I18n.t('.car_class') ,collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
.col-md-4
= f.input :handover_date, as: :string, label: false
= f.input :return_date, as: :string, label: false
= f.submit class: 'btn btn-success'
search method in car model:
def self.search(params)
self.joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?",
params[:return_date], params[:handover_date]).
joins(:car_class).where("car_classes.id= ?", params[:car_class])
.cars_at_both_locations(params[:handover_location], params[:return_location])
end