Unpermitted parameters - Rails 4.1.1, Ruby 2.1.2 - ruby

I cannot seem to get to the bottom of where I am going wrong. My "order.rb" fields populate ok, but I can't get the "order_row" table values to populate. I just keep getting the following error in terminal(not worried about date for now, should be ok with that)...
Unpermitted parameters: date(i), order_row
Customer model(customer.rb)...
class Customer < ActiveRecord::Base
has_many :orders, dependent: :destroy
end
Order model(order.rb)...
class Order < ActiveRecord::Base
belongs_to :customer
has_many :order_rows, dependent: :destroy
accepts_nested_attributes_for :order_rows
end
Order_Row model(order_row.rb)
class OrderRow < ActiveRecord::Base
belongs_to :order
end
(orders_controller.rb)....
def new
#order = Order.new
end
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to(#order, :notice => 'Order was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
private
def order_params
params.require(:order).permit(:customer_id, :date, :total,
:order_row_attributes => [:description, :quantity, :price, :order_id])
end
Form code on new.html.haml
= semantic_form_for #order do |f|
= f.input :customer_id, :as => :select, :collection => Hash[Customer.all.map{|c| [c.company,c.id]}]
= f.input :date
= f.fields_for :order_row do |ff|
= ff.input :description
= ff.input :quantity
= ff.input :price
= ff.hidden_field :order_id
= f.input :total
= f.action :submit, :as => :button

The problem is this line order_row_attributes.It should be order_rows_attributes. And with the date not being permitted,try changing the date attribute to some name like order_date.
This should work
private
def order_params
params.require(:order).permit(:customer_id, :order_date, :total,
:order_rows_attributes => [:description, :quantity, :price, :order_id])
end

I got it working by changing the new method to....
def new
#order = Order.new
#order.order_rows.build
end
So combination of this and Pavans answer did the trick.

Related

Rails - Unknown Attribute - Unable to add a new field to a form on create/update

Hello I am new to Rails.
Here is my controller/projects_controller.rb code
def create
#project = current_user.projects.new(project_params)
##project.website = params[:website]
respond_to do |format|
if #project.save
Member.create!(
user_id: current_user.id,
project_id: #project.id,
project_manager: true,
status: "ready")
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 update
##project.website = params[:website]
respond_to do |format|
# if (#project.active_was == true) &&
# disabled = true
# end
if #project.update(project_params)
# if disabled && (#project.active == false)
# flash[:modal] = true
# end
#project.website = params[:website]
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: #project }
else
format.html { render :edit }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def project_params
params.require(:project).permit(
:university_id,
:project_name,
:location,
:tagline,
:photos,
:industry,
:category,
:description,
:category_id,
:expertise_string,
:website,
:active,
:slug,
:project_groups_attributes => [:id, :active, :university_id, :user_group_id]
)
end
Here is the code for my model/project.rb
class Project < ActiveRecord::Base
# has_and_belongs_to_many :users
has_many :members, :dependent => :destroy
has_many :users, :through => :members
has_one :survey
has_many :project_groups, foreign_key: "project_id", dependent: :destroy
has_many :groups, :through => :project_groups, :source => :university
accepts_nested_attributes_for :project_groups, :allow_destroy => true
has_many :project_expertises, foreign_key: "project_id",
dependent: :destroy
has_many :expertises, :through => :project_expertises, :source => :expertise
belongs_to :category
belongs_to :website
Here is my db/migrate/[timestamp]_create_projects.rb code
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.integer :university_id
t.string :project_name
t.string :tagline
t.string :photos
t.string :industry
t.integer :category
t.text :description
t.text :website
t.timestamps
end
end
end
Why can I not add the 'website' field to this? Is there something more that I have to do?
As per your comment there is not any Website model available so there is not any meaning of putting association:
Simply remove this line from your project model
belongs_to :website
In Project model you've specified relation belongs_to :website. In migration schema instead of:
t.text :website
must be something like that:
t.references :website, index: true, foreign_key: true
When you generate model instead of
rails g ... website:text use rails g ... website:references.
ActiveRecord can't find foreign key to associate Project with Website.

Rails 4 dynamic form nested attributes without hidden input

Previously I asked a question about building an attendance list getting the students and building a check list to mark attendance and came up with this.
def new
#attendance_list = #classroom.attendance_lists.new
#attendance_list.attendances = #classroom.student_ids.map do |student_id|
#attendance_list.attendances.build(student_id: student_id)
end
end
def create
#attendance_list = #classroom.attendance_lists.new(attendance_list_params)
#attendance_list.classroom_id = params[:classroom_id]
respond_to do |format|
end
params
params.require(:attendance_list)
.permit(:post_date, :remark,
attendances_attributes: [:student_id, :attended, :remarks ])
with simple fields
= simple_form_for [#school, #classroom, #attendance_list] do |f|
= f.input :post_date
= f.input :remark
= f.simple_fields_for :attendances do |g|
** you see i needed a hidden student_id **
= g.input :student_id, as: :hidden
......
model
class AttendanceList < ActiveRecord::Base
belongs_to :classroom
has_many :attendances
has_many :students, :through => :attendances
accepts_nested_attributes_for :attendances
end
class Attendance < ActiveRecord::Base
belongs_to :student
belongs_to :attendance_list
end
class Classroom < ActiveRecord::Base
belongs_to :school
has_and_belongs_to_many :students
has_many :attendance_lists
validates :class_name, presence: true
end
how do I do without the hidden input because this line doesn't seem to work.
build(student_id: student_id)
class AttendanceList < ActiveRecord::Base
belongs_to :classroom
has_many :attendances
has_many :students, :through => :attendances
accepts_nested_attributes_for :attendances
end
class Attendance < ActiveRecord::Base
belongs_to :student
belongs_to :attendance_list
end
class Classroom < ActiveRecord::Base
belongs_to :school
has_and_belongs_to_many :students
has_many :attendance_lists
validates :class_name, presence: true
end
class Student < ActiveRecord::Base
has_many :attendances
has_many :attendance_lists, :through => :attendances
end
view file
= simple_form_for #student do |f|
= f.simple_fields_for :attendances do |g|
** your code **

Form data is not stored in DB

My models:
class LineItem < ActiveRecord::Base
attr_accessible :itemable, :adults, :children
belongs_to :itemable, polymorphic: true
belongs_to :lead
belongs_to :cart
end
class Lead < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
class House < ActiveRecord::Base
has_many :line_items, :as => :itemable
end
class Appartment < ActiveRecord::Base
has_many :line_items, :as => :itemable
end
item_controller
def create
#line_item = #cart.line_items.build itemable: #object
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item.cart,
notice: 'Vakantiehuis toegevoegd in lijst.' }
format.json { render action: 'show',
status: :created, location: #line_item }
else
format.html { render action: 'new' }
format.json { render json: #line_item.errors,
status: :unprocessable_entity }
end
end
end
private
def create_object
id = params[:house_id] || params[:appartment_id]
model = "House" if params[:house_id]
model = "Apartment" if params[:appartment_id]
model = model.constantize
#object = model.find(id)
end
lead_controller
def create
#lead = Lead.new(lead_params)
#lead.add_line_items_from_cart(#cart)
#lead.save
end
cart_controller
def create
#cart = Cart.new(cart_params)
end
private
def cart_params
params[:cart]
end
When the items are added from the house and aparment page..the visitor goes to the cart show template. The visitor can fill in number of adutls and children by a form (select).
- #cart.line_items.each do |item|
%tr.CartProduct
%td
.CartDescription
%p
= link_to item.itemable.name, polymorphic_url([item.itemable.country, item.itemable.region, item.itemable])
%td.CartProductThumb
%div
- item.itemable.attachments.take(1).each do |a|
= link_to(image_tag(a.file.url(:thumb)))
%td
.col-md-10
= form_for(item) do |f|
= f.select :adults, ['1', '2', '3', '4', '5'], :class => 'form-control'
%td
.col-md-10
= form_for(item) do |f|
= f.select :children, ['1', '2', '3', '4', '5'], :class => 'form-control'
= button_to "Checkout", new_lead_path, method: :get
The [cart_id] and the polymorphic [itemable_type][itemable_id]values are correctly stored in the line_items table, but not the form data :adults and children. What am i doing wrong ? Thanks remco
logfile:
Started POST "/nl/leads" for 127.0.0.1 at 2014-09-04 11:55:25 +0200
Processing by LeadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jmWa/Q/+SGsS+ed7zEB5+w5tiY2ywkEx3dQeVt9roKs=", "lead"=>{"firstname"=>"test ", "lastname"=>"", "email"=>"", "extra"=>"", "telephone"=>""}, "commit"=>"submit", "nl"=>"nl"}
Cart Load (0.2ms) SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = 25 LIMIT 1
LineItem Load (0.2ms) SELECT `line_items`.* FROM `line_items` WHERE `line_items`.`cart_id` = 25
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `leads` (`created_at`, `email`, `extra`, `firstname`, `lastname`, `telephone`, `updated_at`) VALUES ('2014-09-04 09:55:25', '', '', 'test ', '', '', '2014-09-04 09:55:25')
SQL (0.2ms) UPDATE `line_items` SET `lead_id` = 8, `updated_at` = '2014-09-04 09:55:25' WHERE `line_items`.`id` = 191
(8.8ms) COMMIT
Redirected to http://0.0.0.0:3000/nl/leads/8
Completed 302 Found in 40ms (ActiveRecord: 9.7ms)

Update multiple records using one form

I have a following situation: user has multiple assets and each asset has one asset_detail record.
Models:
class User < ActiveRecord::Base
has_many :assets
end
class Asset < ActiveRecord::Base
has_one :asset_detail
belongs_to :user
accepts_nested_attributes_for :asset_detail,
:allow_destroy => false
attr_accessible # ...
end
class AssetDetail < ActiveRecord::Base
belongs_to :asset
attr_accessible # ...
end
Controller actions:
def edit
#user = current_user
#assets = Asset.all
end
def update
#user = current_user
#user.update_attributes(params["user"])
end
View:
= form_for #user, url: 'update action url' do |f|
= f.fields_for :assets do |ff|
= ff.text_field :title
= ff.fields_for :asset_detail do |fff|
= fff.text_field :value
The problem is that all the form fields are populated properly but i'm not able to save them. The form is sent without any error but the data is not updated.
I think your models should look like this:
class User < ActiveRecord::Base
attr_accessible :assets_attributes #...
has_many :assets
accepts_nested_attributes_for :assets_attributes
end
class Asset < ActiveRecord::Base
attr_accessible :asset_detail_attrbutes # ...
has_one :asset_detail
belongs_to :user
accepts_nested_attributes_for :asset_detail_attributes,
:allow_destroy => false
end
the reason being, you need to be able to set the attributes via the attributes hash passed to each model. HTH!

How to pass user_id to nested_resource model?

I have a small project setup with devise and cancan. There are User, Project, Responsible and Task Models. Project has nested Tasks. Each Project is assigned to one or multiple users. The task model has a name, user_id and project_id. Authentication and Authorization is working like expected.
When adding a new Task (only an input for name) the project_id gets automatically passed to model/table (i think this is because of routing) but not the user_id.
Do i have to pass the user_id in a hidden_field or is it somehow possible to set this in a before filter?
Can somebody give a hint on howto set user_id in taskcontroller?
Thanks
# Routes
resources :projects do
resources :tasks
end
#Models
class User < ActiveRecord::Base
has_many :responsibilities, :dependent => :destroy
has_many :projects, :through => :responsibilities
has_many :tasks, :dependent => :destroy
...
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
...
class Task < ActiveRecord::Base
belongs_to :project
belongs_to :user
...
# Tasks Controller with all Task.find/new/update/...
# methods removed like explained in cancan manual
class TasksController < ApplicationController
load_and_authorize_resource :project
load_and_authorize_resource :task, :through => :project
...
def create
respond_to do |format|
if #task.save
format.html { redirect_to [#project, #task], notice: 'created.' }
else
format.html { render action: "new" }
end
end
# Task Form View
<%= semantic_form_for [#project, #task] do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<% end %>
<%= f.actions %>
<% end %>
Update
It seems to work with a before filter. Is this the right way?
class TasksController < ApplicationController
before_filter :set_user, :only => [:create]
load_and_authorize_resource :client
load_and_authorize_resource :task, :through => :client, :shallow => true
...
def set_user()
params[:task][:user_id] = current_user.id.to_s
end
...
if you are using devise you can just pass in the create action you user_id
def create
#task.user = current_user
respond_to do |format|
if #task.save
format.html { redirect_to [#project, #task], notice: 'created.' }
else
format.html { render action: "new" }
end
end
not quiet sure if this is what you mean

Resources