Issue saving in nested form - ruby-on-rails

I followed thos steps http://railscasts.com/episodes/197-nested-model-form-part-2 and changed purchase_product "survey" and supplier_product as "question" but is not saving and also not saving nested attributes.
Here is the controller /app/controller/purchase_product_controller.rb
class PurchaseProductController < ApplicationController
def new
#purchase = PurchaseProduct.new
1.times do
supplier_product = #purchase.supplier_products.build
end
end
def create
#purchase = PurchaseProduct.new(params[:purchase])
if #purchase.save
flash[:notice] = "Successfully created purchase."
redirect_to :action=>"index"
else
render :action => 'new'
end
end
end
Here models:
class PurchaseProduct < ActiveRecord::Base
has_many :supplier_products
accepts_nested_attributes_for :supplier_products ,:allow_destroy => true
end
class SupplierProduct < ActiveRecord::Base
belongs_to :purchase_product
end
Here is my routes: /config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.root :controller => "purchase_product", :action=>"index"
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
Here is the view: /app/view/purchase_product/new.html.erb
<% form_for #purchase, :url => {:controller=>"purchase_product",:action=>'create'}, :html => {:id => 'new_product_form'} do |f| %>
Name: <%= f.text_field :name %>
<% f.fields_for :supplier_products do |builder| %>
<%= render "supplier_product_fields", :f => builder %>
<% end %>
<p><%= link_to_add_fields "Add Supplier Product", f, :supplier_products %></p>
<p><%= f.submit "Submit" %></p>
<% end %>
Here is the partial view: /app/view/purchase_product/_supplier_product_fields.html.erb
<div class="fields">
Type Money: <%= f.select(:type_money,([["%", 0], ["$", 1] ]) ) %>
Cost: <%= f.text_field :amount %><%= link_to_remove_fields "remove", f %>
</div>
But was not saving and got this log:
Processing PurchaseProductController#create (for 127.0.0.1 at 2014-08-06 13:48:31) [POST]
Parameters: {"purchase_product"=>{"name"=>"testing", "supplier_products_attributes"=>{"0"=>{"amount"=>"333", "type_money"=>"0", "_destroy"=>""}}}, "commit"=>"Submit"}
PurchaseProduct Columns (0.6ms) SHOW FIELDS FROM `purchase_products`
SQL (0.1ms) BEGIN
PurchaseProduct Create (0.0ms) Mysql::Error: Column 'name' cannot be null: INSERT INTO `purchase_products` (`name`, `created_at`, `updated_at`) VALUES(NULL, '2014-08-06 18:48:31', '2014-08-06 18:48:31')
SQL (0.1ms) ROLLBACK
ActiveRecord::StatementInvalid (Mysql::Error: Column 'name' cannot be null: INSERT INTO `purchase_products` (`name`, `created_at`, `updated_at`) VALUES(NULL, '2014-08-06 18:48:31', '2014-08-06 18:48:31')):
I solved the problem of saving, changing this param in the view and saved but is not saving the other attributes
Name: <%= text_field_tag "name",#name,:name=>"purchase_product[name]" %>
I got this LOG:
Processing PurchaseProductController#create (for 127.0.0.1 at 2014-08-06 14:00:04) [POST]
Parameters: {"purchase_product"=>{"name"=>"TESTING", "supplier_products_attributes"=>{"0"=>{"amount"=>"100", "type_money"=>"0", "_destroy"=>""}}}, "commit"=>"Submit"}
PurchaseProduct Columns (0.7ms) SHOW FIELDS FROM `purchase_products`
SQL (0.1ms) BEGIN
PurchaseProduct Create (0.3ms) INSERT INTO `purchase_products` (`name`, `created_at`, `updated_at`) VALUES('TESTING', '2014-08-06 19:00:04', '2014-08-06 19:00:04')
SQL (37.0ms) COMMIT
Redirected to http://localhost:3000/
Completed in 44ms (DB: 38) | 302 Found [http://localhost/purchase_product/create]
I spent a long time searching about a solution also I recreated the project several times.
Attributes from supplier products are not saving.
Please somebody can help me with this issue?

In your controller you are grabbing the purchase key from the params hash.
#purchase = PurchaseProduct.new(params[:purchase])
But the parameters you need are actually going to be in params[:purchase_product].
#purchase = PurchaseProduct.new(params[:purchase_product])
When you use the form_for helper, the key will be named after the model which the form is built around. In your case it is a PurchaseProduct, hence why they'll be in params[:purchase_product]

Related

Rails 4 Nested Forms, Error: Unpermitted parameter: order_item

My goal is to create a new Order and an associated OrderItem using the same form.
Models
class Order < ActiveRecord::Base
belongs_to :user
has_many :order_items, dependent: :destroy
accepts_nested_attributes_for :order_items
validates_associated :order_items
end
class OrderItem < ActiveRecord::Base
belongs_to :order
default_scope -> { order(created_at: :desc) }
end
View
<% #items.each do |item| %>
<%= form_for(#order) do |f| %>
<%= f.hidden_field :user_id, :value => session[:user_id] %>
<%= f.fields_for :order_items do |oi| %>
<%= oi.hidden_field :product_id, :value => item.id %>
<%= oi.hidden_field :price, :value => item.price %>
<%= oi.number_field :quantity, value: 1, class: 'form-control', min: 1 %>
<% end %>
<%= f.submit "Buy Now", class: "btn btn-primary" %>
<% end %>
Controller
def new
#order = Order.new
#order.order_items.build
end
def create
#order = Order.new(order_params)
if #order.save
redirect_to cart_path
else
redirect_to root_url
end
end
private
def order_params
params.require(:order).permit(:user_id, :custom_item_id, order_items_attributes: [:product_id, :price, :quantity])
end
When submitting the nested form data to the database, the error message Unpermitted parameter: order_item gets returned and only the order data is saved.
Update <-- This is resolved
When I remove the "f." from <%= f.fields_for the form renders correctly and order_params includes the order_items data. This is interesting because the RailsGuide for Form Helpers includes the "f." http://guides.rubyonrails.org/form_helpers.html#nested-forms
Parameter
{"utf8"=>"✓", "authenticity_token"=>"<TOKEN>", "order"=>{"user_id"=>"1", "order_item"=>{"product_id"=>"5", "price"=>"120.0", "quantity"=>"1"}}, "commit"=>"Buy Now"}
The data still does not save to the corresponding models.
Update 2 <-- This is resolved
Updated the createaction in the controller to if #order.save!, below is the error message:
Validation failed: Order items order can't be blank, Order items product can't be blank, Order items quantity can't be blank, Order items price can't be blank, Order items is invalid
I believe that the mistake is in this line of code #order.order_items.build(order_params[:order_items_attributes]) but I am not sure what I need to change.
Update 3 Unpermitted parameter: order_item Error message
From the terminal:
Processing by OrdersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=><TOKEN>, "order"=> "user_id"=>"1", "order_item"=>{"product_id"=>"5", "price"=>"120.0", quantity"=>"1"}}, "commit"=>"Buy Now"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Unpermitted parameter: order_item
(0.2ms) begin transaction
SQL (1.4ms) INSERT INTO "orders" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?) [["user_id", 1], ["created_at", "2016-03-18 14:58:21.724246"], ["updated_at", "2016-03-18 14:58:21.724246"]]
(14.4ms) commit transaction
The order_itemsdata does not get saved.
First, it seems like your association is incorrect in OrderItem. It should be belongs_to :order instead of belongs_to :order_item_params.
Second, I believe your form should say <%= f.fields_for :order_items do |oi| %> (:order_items not :order_item)
Finally, you should not need to do this in your controller: #order.order_items.build(order_params[:order_items_attributes])
Controller
def create
#order = Order.new(order_params)
if #order.save
redirect_to cart_path
else
redirect_to root#url
end
end
def order_params
params.require(:order).permit(:user_id, :custom_item_id, order_items_attributes: [:product_id, :price, :quantity])
end
The view that rendered the form was not in another controller and not in the orders controller. The show action of tht view did not include an instance variable for order_items. This caused the error messages. Thank you for all of your help. For anyone looking for resources for nested forms below are some helpful resources.
YouTube Video Instructions API dock for fields_for
Go Rails video for Form Nested Attributes and Fields For in Rails
Active Record Nested Attributes
Rails Guide: Active Record Associations

Issue getting ActiveRecord::StatementInvalid on new record

I'm tryint to save information but seems to be hard.
Here my controller /app/controllers/finance_management/voucher_controller.rb
class FinanceManagement::VoucherController < ActionController::Base
def new
#voucher = Voucher.new
end
def create
Voucher.create(params[:voucher])
end
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
end
Here is my model /app/models/voucher.rb
class Voucher < ActiveRecord::Base
end
Here is my view /app/finance_management/voucher/new.html.erb
<%= form_for :obj_voucher, :url => { :controller => "finance_management/voucher", :action => "create" } do |f| %>
Number<%= f.text_field :voucher_num %>
<%= f.submit :submit %>
<% end %>
Here my routes.rb
Rails.application.routes.draw do
namespace :finance_management do
resources :voucher
end
match ':controller(/:action(/:id(.:format)))', via: [:get, :post]
end
Here my logs
Started POST "/finance_management/voucher" for 127.0.0.1 at 2016-01-17 21:00:39 -0500
Processing by FinanceManagement::VoucherController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"222222=", "voucher"=>{"voucher_num"=>"1111"}, "commit"=>"submit"}
(0.1ms) BEGIN
SQL (1.5ms) INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
(0.2ms) ROLLBACK
Completed 500 Internal Server Error in 5ms (ActiveRecord: 1.8ms)
ActiveRecord::StatementInvalid (Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')):
I tried several ways but cannot save information but got errors:
<%= form_for :user, :url => {:controller=>"finance_management/voucher",:action=>'create'} do |f|%>
<%= form_for #user, :url => {:controller=>"finance_management/voucher",:action=>'create'} do |f|%>
Also changed this:
def create
#voucher= Voucher.create(params[:voucher_params])
end
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
The field is not saving
Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
Try:
def create
Voucher.create(voucher_params)
end
ActionController params can't be used in ActiveModel mass assignment directly, you have to use strong parameters instead.
For benefit of the doubt, here's how the code should be structured:
#config/routes.rb
namespace :finance_management do
resources :vouchers
end
#app/controllers/financial_management/vouchers_controller.rb
class FinanceManagement::VouchersController < ActionController::Base
def new
#voucher = Voucher.new
end
def create
#voucher = Voucher.new voucher_params
#voucher.save
end
private
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
end
#app/views/finance_management/vouchers/new.html.erb
<%= form_for [:financial_management, #voucher] do |f| %>
<%= f.text_field :voucher_num, placeholder: "Number" %>
<%= f.submit %>
<% end %>

Rails 4: render controller/action again when validation fails

There are already a couple of questions addressing this issue:
render/redirect to new action when validation fails (rails)
Keeping validation errors after redirect from partial back to the same page that has the partial
I tried to implement some of the solutions recommended but did not manage fixing my issue.
So here we go.
In my Rails 4 app, there are four models:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
has_many :invitations, :class_name => "Invite", :foreign_key => 'recipient_id'
has_many :sent_invites, :class_name => "Invite", :foreign_key => 'sender_id'
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
has_many :invites
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Invite < ActiveRecord::Base
belongs_to :calendar
belongs_to :sender, :class_name => 'User'
belongs_to :recipient, :class_name => 'User'
end
Here, we are going to focus on the Invite and the Calendar models.
In the calendar edit view, I have a form to create a new invite:
<h2>Edit <%= #calendar.name %> calendar</h2>
<%= render 'form' %>
<h2>Invite new users to <%= #calendar.name %> calendar</h2>
<%= form_for #invite , :url => invites_path do |f| %>
<%= f.hidden_field :calendar_id, :value => #invite.calendar_id %>
<%= f.label :email %>
<%= f.email_field :email %>
<%= f.label "Role" %>
<%= f.radio_button(:recipient_role, "Editor") %>
<%= f.label "Editor" %>
<%= f.radio_button(:recipient_role, "Viewer") %>
<%= f.label "Viewer" %>
<%= f.submit 'Send' %>
<% end %>
<%= link_to 'Show', calendar_path %> |
<%= link_to 'Back', calendars_path %>
–––––
UPDATE: please note that I have defined a calendars.html.erb layout for my calendar views, including the following code to display alerts:
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>">
<%= value %>
</div>
<% end %>
–––––
In the Invite model, I want to validate the presence of :email and :recipient_role (both values submitted by the user through the form), so I added this to the Invite model:
validates :email, :recipient_role, presence: true
And I would like users to be redirected to the form with an error message if they forgot to fill one of these two fields, which I implemented with the following code in the InvitesController:
class InvitesController < ApplicationController
def create
# some code
if #invite.save
# some code
else
format.html { render :template => "calendars/edit", notice: 'Invitation could not be sent.' }
end
redirect_to calendar_path(#calendar), notice: 'Invitation was successfully sent.'
end
private
def invite_params
params.require(:invite).permit(:email, :calendar_id, :recipient_role)
end
end
In particular, I thought that the line format.html { render :template => "calendars/edit", notice: 'Invitation could not be sent.' } would allow me to do what I wanted, as recommended here.
However, when I try to submit the form with at least an empty field, I get the following error:
ArgumentError in InvitesController#create
too few arguments
end
else
format.html { render :template => "calendars/edit", notice: 'Invitation could not be sent.' }
end
redirect_to calendar_path(#calendar), notice: 'Invitation was successfully sent.'
end
And this is the server log:
Processing by InvitesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p+yxM9Tw3JiNw/6Chv9//N8uvWhMy0TqrudTu0y9D9zXCl6kK2LtCqPu1rvTGv5gOMBuv2RK/IX2MBpWUTelZw==", "invite"=>{"calendar_id"=>"3", "email"=>"test#example.com"}, "commit"=>"Send"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Calendar Load (0.1ms) SELECT "calendars".* FROM "calendars" WHERE "calendars"."id" = ? LIMIT 1 [["id", 3]]
(0.0ms) begin transaction
(0.0ms) rollback transaction
Completed 500 Internal Server Error in 27ms (ActiveRecord: 1.3ms)
ArgumentError (too few arguments):
app/controllers/invites_controller.rb:16:in `format'
app/controllers/invites_controller.rb:16:in `create'
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1#global/gems/actionpack-4.2.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (3.7ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1#global/gems/actionpack-4.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.5ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1#global/gems/actionpack-4.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1#global/gems/actionpack-4.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (54.0ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.3ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.4ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.3ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (36.5ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.5ms)
Rendered /Users/TXC/.rvm/gems/ruby-2.2.1/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (83.2ms)
What am I doing wrong?
Do the following things please
def create
# some code
if #invite.save
redirect_to calendar_path(#calendar), notice: 'Invitation was successfully sent.'
else
render template: "calendars/edit", notice: 'Invitation could not be sent.'
end
end

Using cocoon gem, but can't save data after first input field

I've tried to implement cocoon in my application, but having trouble saving data after the first input field.
I tried following the example, but no luck.
I'm able to save the first field into database, but nothing happens on the other fields when I add more.
_form.html.erb
<%= simple_form_for(#project) do |f| %>
<%= f.input :project_name %>
<%= f.hidden_field :user_id %>
<div id="tasks">
<%= f.simple_fields_for :tasks do |g| %>
<%= render 'task_fields', :f => g %>
<% end%>
<%= link_to_add_association 'add task', f, :tasks %>
</div>
<%= f.button :submit %>
<% end %>
_task_fields.html.erb
<li class="control-group nested-fields">
<div class="controls">
<%= f.label :task %>
<%= f.text_field :task %>
</div>
<%= link_to_remove_association "remove task", f %>
</li>
Controller
params.require(:project).permit(
:user_id, :project_name,
tasks_attributes: [:id, :task, :_destroy])
And I added:
//= require cocoon
in application.js
Project Model
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
accepts_nested_attributes_for :tasks, :reject_if => :all_blank, allow_destroy: true
end
Task Model
class Task < ActiveRecord::Base
belongs_to :project
end
I think I got this correct? I'm able to click on "add task" link and a new field pops up, but those new fields doesn't save.
EDIT from POST in console
Processing by ProjectsController#create as HTML
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"blah",
"project"=>{"project_name"=>"cocoon test",
"tasks_attributes"=>{
"0"=>{"task"=>"fix this!",
"_destroy"=>"false"
}}},
"commit"=>"Create Project"}
(0.2ms) begin transaction
SQL (1.5ms) INSERT INTO "projects" ("project_name", "created_at", "updated_at") VALUES (?, ?, ?) [["project_name", "cocoon test"], ["created_at", "2015-07-15 03:26:09.444377"], ["updated_at", "2015-07-15 03:26:09.444377"]]
SQL (0.4ms) INSERT INTO "tasks" ("task", "project_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["task", "fix this!"], ["project_id", 8], ["created_at", "2015-07-15 03:26:09.450324"], ["updated_at", "2015-07-15 03:26:09.450324"]]
(8.4ms) commit transaction
Redirected to http://localhost:3000/projects/8
Completed 302 Found in 24ms (ActiveRecord: 10.4ms)
EDIT 2 posting project controller methods create and new
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: #project }
else
format.html { render :new }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def new
#project = Project.new
#project.tasks.build
end

has_many belongs_to relationship not passing through params

I am making a small store admin
Product.rb
class Product < ActiveRecord::Base
has_many :product_options
accepts_nested_attributes_for :product_options
end
ProductOption.rb
class ProductOption < ActiveRecord::Base
belongs_to :product
end
products_controller.rb
class Admin::ProductsController < AdminApplicationController
def index
#products = Product.all
end
def new
#product = Product.new
end
def create
#product = Product.new(product_params)
if #product.save
redirect_to admin_products_path
end
#product_option = #product.product_options.create(params[:product_option])
end
def edit
#product = Product.find(params[:id])
end
def update
#product = Product.find(params[:id])
if #product.update(product_params)
redirect_to admin_products_path
end
end
def destroy
#product = Product.find(params[:id])
#product.destroy
flash[:notice] = "#{#product.name} has been deleted."
redirect_to admin_products_path
end
def upload
uploaded_io = params[:id]
File.open(Rails.root.join('public', 'product_pics', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
private
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id, :option_name, :product_option )
end
end
product_option_controller.rb
class Admin::ProductOptionsController < AdminApplicationController
def index
#product_options = ProductOption.all
end
def new
#product_option = ProductOption.new
end
def create
#product_option = ProductOption.new(product_option_params)
end
def show
#product_option = ProductOption.find(params[:id])
end
end
private
def product_option_params
params.require(:product_option).permit(:option_name, :ranking, :total_redeemed, :product_id)
end
end
_form.html.erb
<%= simple_form_for([:admin, #product] , :html => {:multipart => true}) do |f| %>
<section class="main_content-header">
<div class="main_content-header-wrapper">
<nav class="main_content-breadcrumbs">
<ul class="breadcrumbs">
<li><%= link_to "All Products", admin_products_path %></li>
<h1> Edit Product </h1>
</ul>
</nav>
<div class="main_content-header-save">
<%= link_to "Cancel", admin_products_path, id: "main_content-header-save-cancel" %>
<%= f.submit %>
</div>
</div>
</section>
<div class="main_content-section">
<section class="main_content-section">
<div class="main_content-section-area">
<%= f.input :name %>
<%= f.input :product_description %>
<%= f.input :product_detail %>
<%= f.file_field :product_image %>
<p> If this product has options, enter them below</p>
<%= f.simple_fields_for :product_option, #product_option do |option_form| %>
<%= option_form.input :option_name %>
<% end %>
</div>
</section>
</div>
<% end %>
server output: ... keeps saying that :product_option is not permitted
Started POST "/admin/products" for 127.0.0.1 at 2014-10-15 16:13:25 -0700
Processing by Admin::ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t96EMVlDND42HuVUzxWuss2bYDVhBokieTqN2Gz3N9I=", "commit"=>"Create Product", "product"=>{"name"=>"cvncvbn", "product_description"=>"cvbn", "product_detail"=>"", "product_option"=>{"option_name"=>"cvnbnvcb"}}}
Unpermitted parameters: product_option
SQL (1.5ms) BEGIN
SQL (0.4ms) INSERT INTO `products` (`created_at`, `name`, `product_description`, `product_detail`, `updated_at`) VALUES (?, ?, ?, ?, ?) [["created_at", "2014-10-15 23:13:25"], ["name", "cvncvbn"], ["product_description", "cvbn"], ["product_detail", ""], ["updated_at", "2014-10-15 23:13:25"]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/admin/products
SQL (0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `product_options` (`product_id`) VALUES (?) [["product_id", 119]]
(0.3ms) COMMIT
Completed 302 Found in 10ms (ActiveRecord: 2.8ms)
Started GET "/admin/products" for 127.0.0.1 at 2014-10-15 16:13:25 -0700
Processing by Admin::ProductsController#index as HTML
Product Load (0.3ms) SELECT `products`.* FROM `products`
Rendered admin/products/index.html.erb within layouts/admin (11.7ms)
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 7 ORDER BY `users`.`id` ASC LIMIT 1
Rendered admin/_header.html.erb (1.4ms)
Rendered admin/_nav.html.erb (0.4ms)
Completed 200 OK in 21ms (Views: 19.8ms | ActiveRecord: 0.6ms)
The record gets saved, so in the products options table there is just the product_id, .. but no other params....have tried a million things over the past 6 hours... so i dont really have a list of all the possible options, .. but if someone can see a glaring mistake your wisdom would be greatly appreciated.
--------------------------------------------------------------------------------------------
I figured it out, i was not using accepts_nested_attributes correctly these are the changes I had to get it all work.
-deleted the product_options controller (it was not needed)
-changed the product_params:
private
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id,
:product_options_attributes => [:id, :option_name, :ranking, :total_redeemed, :product_id])
end
end
-deleted this line from the create action of the products controller
#product_option = #product.product_options.create(params[:product_option])
-added this line to the new action of the products controller
#product.product_options.build
-added an s to the ":product_option" in this loop (and deleted the '#product_option")
<%= f.simple_fields_for :product_option, #product_option do |option_form| %>
<%= option_form.input :option_name %>
<% end %>
the main change was adding the S... without it nested attributes was not being called at all
Try something like
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id, :option_name, product_option: [:option_name] )
end

Resources