Rails does not create associated model - ruby-on-rails

I created a form where a user can create a profile. In the form the user can select multiple companies. A profile has many companies through a join-table named profile_companies. My code does create a new profile, but it does not create the association. Meaning that when I hit in the console: Profile.last.companies it returns an empty array. When I check the params before a profile is created, it does show me a full array for company_ids. So it looks like it cannot pass these values and create the association. Does anyone have an idea where the error is?
Here is my Profile model:
class Profile < ApplicationRecord
belongs_to :user
has_many :profile_companies
has_many :companies, through: :profile_companies
STATUSES = ["currently looking for a job", "employed but open for a new challenge"]
validates :status, inclusion: {in: STATUSES}
end
here is my company model:
class Company < ApplicationRecord
has_many :vacancies
has_many :profile_companies
has_many :profiles, through: :profile_companies
end
here is my profiles controller:
class ProfilesController < ApplicationController
def new
#profile = Profile.new
end
def create
#profile = Profile.new(params_profile)
if #profile.save
redirect_to profile_path
else
render :new
end
end
private
def params_profile
params.require(:profile).permit(:status, :name, :content, :company_ids)
end
end
And here is my pry to show the params handed to the controller:
[1] pry(#<ProfilesController>)> params[:profile] => <ActionController::Parameters {"name"=>"test 4", "status"=>"employed but open for a new challenge", "company_ids"=>["", "31", "34"], "content"=>"test 4"} permitted: false>
And here are my Logs:
Started POST "/profiles" for ::1 at 2019-08-05 22:54:36 +0200
Processing by ProfilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bmmqCdtWvTcDjlbR6yGrdZTGj+t3O2NMwNKanY5qP84eCSsCuBVF4SdzDkQ+0YOe5q+CapWx5NLaftunZ+ANSg==", "profile"=>{"name"=>"test 4", "status"=>"employed but open for a new challenge", "company_ids"=>["", "17", "31", "32"], "content"=>"rrr"}, "commit"=>"Save your profile"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 16], ["LIMIT", 1]]
Unpermitted parameter: :company_ids
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Rendering profiles/new.html.erb within layouts/application
Company Load (2.6ms) SELECT "companies".* FROM "companies"
CACHE Company Load (0.0ms) SELECT "companies".* FROM "companies"
CACHE Company Load (0.0ms) SELECT "companies".* FROM "companies"
Rendered profiles/new.html.erb within layouts/application (29.2ms)
Rendered shared/_navbar.html.erb (1.4ms)
Rendered shared/_flashes.html.erb (0.4ms)
Completed 200 OK in 178ms (Views: 170.6ms | ActiveRecord: 3.2ms)

A couple of things. First, as you can see from the Unpermitted parameter: :company_ids message:
Started POST "/profiles" for ::1 at 2019-08-05 22:54:36 +0200
Processing by ProfilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bmmqCdtWvTcDjlbR6yGrdZTGj+t3O2NMwNKanY5qP84eCSsCuBVF4SdzDkQ+0YOe5q+CapWx5NLaftunZ+ANSg==", "profile"=>{"name"=>"test 4", "status"=>"employed but open for a new challenge", "company_ids"=>["", "17", "31", "32"], "content"=>"rrr"}, "commit"=>"Save your profile"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 16], ["LIMIT", 1]]
Unpermitted parameter: :company_ids
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Rendering profiles/new.html.erb within layouts/application
Company Load (2.6ms) SELECT "companies".* FROM "companies"
CACHE Company Load (0.0ms) SELECT "companies".* FROM "companies"
CACHE Company Load (0.0ms) SELECT "companies".* FROM "companies"
Rendered profiles/new.html.erb within layouts/application (29.2ms)
Rendered shared/_navbar.html.erb (1.4ms)
Rendered shared/_flashes.html.erb (0.4ms)
Completed 200 OK in 178ms (Views: 170.6ms | ActiveRecord: 3.2ms)
...you are using permit incorrectly and company_ids, therefore, is not being permitted.
It should look something more like:
def params_profile
params.require(:profile).permit(:status, :name, :content, company_ids: [])
end
...since company_ids is an array. Permitted arrays should go at the end of the permit list, see the docs for more information.
Second, your Profile model doesn't have a company_ids attribute. So, you may get an error when you do:
#profile = Profile.new(params_profile)
(TBH, I forget how smart (or not) rails is in this type of circumstance.) Which is a whole other thing you'll have to deal with.
Third, your Profile model includes belongs_to :user, but you never assign a user which is why your transaction is getting the ROLLBACK. In general, to see why you're getting a ROLLBACK, you can do something like:
if #profile.save!
...and the bang (!) will cause an error and provide an explanation.
To set the user_id, I would suggest you do something like:
#profile = current_user.build_profile(params_profile)
This assumes that User has_one :profile. See the docs for more information.

Related

Rails: Unpermitted parameters: :authenticity_token, :order, :commit. after upgrade

I am upgrading a functional app from Ruby 1.8.7 Rails 3 to Ruby 3 Rails 7: quite a journey and I am almost finished. But I have an order process, which is not running after the upgrade and is difficult for me to debug. The order process consists in a multistep form, rendered through partials and a create function in my Order controller.
In the first step of the multistep form you have to input the shipping details. When trying to get to the next step, I get the following error message in the server log: Unpermitted parameters: :authenticity_token, :order, :commit. Context: ... etc and the note that all validations have failed is rendered in my website.
Started POST "/orders" for ::1 at 2022-02-22 17:24:01 +0100
Processing by OrdersController#create as HTML
Parameters: {"authenticity_token"=>"[FILTERED]", "order"=>{"email"=>"name#example.com", "phone_number"=>"1234567", "ship_to_first_name"=>"John", "ship_to_last_name"=>"Doe", "ship_to_address"=>"Pennsylvania Avenue 12", "ship_to_city"=>"Houston", "ship_to_postal_code"=>"12345", "land_id"=>"112", "shipping_service_id"=>"50"}, "commit"=>"Continue"}
Cart Load (0.3ms) SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = 4 LIMIT 1
↳ app/controllers/application_controller.rb:66:in `initialize_cart'
Unpermitted parameters: :authenticity_token, :order, :commit. Context: {controller: OrdersController, action: create, request: #<ActionDispatch::Request:0x00007fee489e8e30>, params: {"authenticity_token"=>"[FILTERED]", "order"=>{"email"=>"name#example.com", "phone_number"=>"1234567", "ship_to_first_name"=>"John", "ship_to_last_name"=>"Doe", "ship_to_address"=>"Pennsylvania Avenue 12", "ship_to_city"=>"Houston", "ship_to_postal_code"=>"12345", "land_id"=>"112", "shipping_service_id"=>"50"}, "commit"=>"Continue", "controller"=>"orders", "action"=>"create"} }
CartItem Load (0.4ms) SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 4
↳ app/models/cart.rb:86:in `inject'
....
This is the same process in the old app.
Started POST "/orders" for 127.0.0.1 at Tue Feb 22 10:02:12 +0100 2022
Processing by OrdersController#create as HTML
Parameters: {"authenticity_token"=>"sometoken", "order"=>{"email"=>"name#example.com", "ship_to_first_name"=>"John", "ship_to_address"=>"Pennsylvania Avenue 12", "ship_to_city"=>"Houston", "land_id"=>"112", "ship_to_last_name"=>"Doe", "ship_to_postal_code"=>"12345", "phone_number"=>"1234567", "shipping_service_id"=>"1"}, "commit"=>"Continue", "utf8"=>"✓"}
Cart Load (0.3ms) SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1 [["id", 6255]]
CartItem Load (0.8ms) SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 6255
ActiveShippingHub Load (0.3ms) SELECT `active_shipping_hubs`.* FROM `active_shipping_hubs` LIMIT 1
(0.5ms) SELECT MAX(`cart_items`.`length`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 6255
(0.5ms) SELECT MAX(`cart_items`.`width`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 6255
Rendered shared/_error_messages.html.erb (0.1ms)
Land Load (0.6ms) SELECT `lands`.* FROM `lands` WHERE `lands`.`id` = 112 LIMIT 1
ShippingService Load (0.5ms) SELECT `shipping_services`.* FROM `shipping_services` WHERE `shipping_services`.`id` = 1 LIMIT 1
ProductVariant Load (0.3ms) SELECT `product_variants`.* FROM `product_variants` WHERE `product_variants`.`id` = 14 LIMIT 1
Image Load (0.3ms) SELECT `images`.* FROM `images` WHERE `images`.`id` = 174 LIMIT 1
Rendered orders/_paymentoptions_step.html.erb (10.6ms)
Rendered orders/new.html.erb within layouts/application (14.0ms)
Rendered layouts/_header.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.5ms)
Completed 200 OK in 68ms (Views: 20.9ms | ActiveRecord: 26.9ms)
My Order create action starts with
def create
session[:order_params].deep_merge!(order_params) if params[:order]
#order = Order.new(session[:order_params])
#shipping_services = #cart.available_shipping_services.joins(:lands).where(lands: {id: #order.land_id})
#order.customer_ip = request.remote_ip
populate_order
#order.current_step = session[:order_step]
...
I have set the order_params in the same controller as strong params:
...
private
def order_params
params.permit(:bill_to_address, :bill_to_city, :bill_to_first_name, :bill_to_last_name, :bill_to_land, :bill_to_land_id, :bill_to_postal_code, :date_payment_reminder, :email, :EULA, :express_token, :land_id, :payment, :date_payment_reminder, :phone_number, :signupnewsletter, :ship_to_address, :ship_to_city, :ship_to_first_name, :ship_to_last_name, :ship_to_postal_code, :shipping_service, :shipping_service_id, :shipping_date, :tracking_number, :order_status, :order_status_id, :stripe_card_token, :TOS)
end
end
I am not sure why I get this error. The use of strong_parameters in newer versions of Rails or the way associations are now verified?
When I turn off all validations in my Order model I still get the same message in my logs, but get the message, that there were problems with the shipping_land, shipping_service and bill_to_land fields: three associations of my Order model.
The associations are set in my Order model as follows:
# Associations
belongs_to :bill_to_land, class_name: "Land", foreign_key: :bill_to_land_id
belongs_to :land, foreign_key: :land_id
belongs_to :order_status
belongs_to :shipping_service
The multistep form is set in orders/new.html.erb
<%= form_for #order do |f| %>
<%= render "#{#order.current_step}_step", :f => f %>
<%= f.submit "Continue" unless #order.payment_options_step? || #order.billing_step? || #order.creditcard_options_step? || #order.last_step? %>
In the multistep form I only gather data and kick this data between steps in the session. The order entry is created only after the final submit.
Why do I get this error message? How can I debug the order session? What data has been written to it...
I hope someone can put me into the right direction.
private
def order_params
params.require(:order).permit(:bill_to_address, :bill_to_city, :bill_to_first_name, :bill_to_last_name, :bill_to_land,
:bill_to_land_id, :bill_to_postal_code, :date_payment_reminder, :email, :EULA, :express_token, :land_id, :payment, :date_payment_reminder, :phone_number, :signupnewsletter, :ship_to_address, :ship_to_city, :ship_to_first_name, :ship_to_last_name, :ship_to_postal_code, :shipping_service, :shipping_service_id, :shipping_date, :tracking_number, :order_status, :order_status_id, :stripe_card_token, :TOS)
end
end

Associations cause "EMPTY" in Active Admin

So I'm learning more about belongs_to and has_many Associations in Rails and am combining it with ActiveAdmin.
I have created a Model "Semester" and a Model "Field". A Semester has many Fields and a Field belongs to Semester.
My field Class looks like this:
class Field < ApplicationRecord
belongs_to :semester
accepts_nested_attributes_for :semester, allow_destroy: true
end
and my Semester class looks like this:
class Semester < ApplicationRecord
has_many :fields
accepts_nested_attributes_for :fields, allow_destroy: true
end
Now I registered the Models with active admin with the following two files:
ActiveAdmin.register Field do
permit_params :name, semesters_attributes: [:name]
end
and
ActiveAdmin.register Semester do
permit_params :name, :fields, fields_attributes: [ :field_id, :name]
end
And now there are two issues that come up upon proceeding that I absolutely can not ged rid off:
1) If I do not add optional: true after belongs_to :semester I will get an error message "must exist" upon trying to create a new Field with a respective Semester.
2) If I do add optional: true after belongs_to :semester I will be able to create a new Field but the "Semester" will just be "EMPTY" in the new field.
The console output of case 2) will look like this:
Started POST "/admin/fields" for 127.0.0.1 at 2018-08-17 15:23:54 +0200
Processing by Admin::FieldsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+GPjjNPOv9GsjXnEtEjBcC0xUMHKKC+YpFLfiUFUOgsgBJ+pLCucscrN0YaTk551GFp4K5lBEI2RW1clw2vCWw==", "field"=>{"semester_id"=>"2", "name"=>"MAVT"}, "commit"=>"Create Field"}
AdminUser Load (0.1ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = ? ORDER BY "admin_users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Unpermitted parameter: :semester_id
(0.0ms) begin transaction
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Field Create (0.6ms) INSERT INTO "fields" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "MAVT"], ["created_at", "2018-08-17 13:23:54.026418"], ["updated_at", "2018-08-17 13:23:54.026418"]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
(12.2ms) commit transaction
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Redirected to http://0.0.0.0:3000/admin/fields/22
Completed 302 Found in 22ms (ActiveRecord: 13.0ms)
Started GET "/admin/fields/22" for 127.0.0.1 at 2018-08-17 15:23:54 +0200
Processing by Admin::FieldsController#show as HTML
Parameters: {"id"=>"22"}
AdminUser Load (0.2ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = ? ORDER BY "admin_users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Field Load (0.1ms) SELECT "fields".* FROM "fields" WHERE "fields"."id" = ? LIMIT ? [["id", 22], ["LIMIT", 1]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Rendering /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activeadmin-1.3.1/app/views/active_admin/resource/show.html.arb
(0.1ms) SELECT COUNT(*) FROM "active_admin_comments" WHERE "active_admin_comments"."resource_type" = ? AND "active_admin_comments"."resource_id" = ? AND "active_admin_comments"."namespace" = ? [["resource_type", "Field"], ["resource_id", 22], ["namespace", "admin"]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
ActiveAdmin::Comment Exists (0.1ms) SELECT 1 AS one FROM "active_admin_comments" WHERE "active_admin_comments"."resource_type" = ? AND "active_admin_comments"."resource_id" = ? AND "active_admin_comments"."namespace" = ? LIMIT ? OFFSET ? [["resource_type", "Field"], ["resource_id", 22], ["namespace", "admin"], ["LIMIT", 1], ["OFFSET", 0]]
↳ /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Rendered /home/divepit/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activeadmin-1.3.1/app/views/active_admin/resource/show.html.arb (73.4ms)
Completed 200 OK in 77ms (Views: 74.9ms | ActiveRecord: 0.5ms)
Thanks in advance for any tips on how to solve this! :)
First things first. Your associations are correct, but as per your associations you should not have field_id in semester table. Instead you should have semester_id in fields table. Also you should change semesters_attributes to semester_attributes
Unpermitted parameter: :semester_id
You should permit semester_id in the fields_attributes
fields_attributes: [ :semester_id, :name]
And finally in Rails 5, whenever a belongs_to association is defined, it is required to have the associated record present by default. To avoid this default behavior, you need to add optional: true

How to create many single select inputs for a has_many association on simple form?

I've created a form using Simple Form in Rails to create new tests. My Test model has a has_and_belongs_to_many association with the Tool Model.
My code gets all tools and groups them into categories (a category is an attribute of a tool). It then creates a single select box for each category (as shown in the image).
- all_tools = Tool.all.group_by(&:category)
- all_tools.each do |category|
= f.association :tools,
collection: category.last,
label: category.first,
label_method: lambda { |tool| "#{tool.name} (#{tool.description})"},
input_html: { multiple: false }
Many select boxes
When choosing a tool from each select box and submitting the form, I get the following error:
found unpermitted parameter: tool_ids
and the there's only one id currently being submitted for the tool_ids instead of an array of ids which I need.
I know this works when the boxes are multiple selects but I only want the user to be able to select one tool from each category and have it submit all tool_ids in an array similar to the way it would if the user was selecting them from a multiple select box.
So my question is, how can I use multiple single select boxes to submit an array of tool_ids in Simple Form?
EDIT:
As requested, I've added the relevant code:
tests_controller:
def create
#test = Test.new(test_params)
#tools = Tool.all.select(:name).distinct
if #test.save
Activity.log(current_user, "Created test #{#test.id}")
redirect_to #test, notice: 'Test was successfully created.'
else
render :new, notice: 'Unable to save Test Details.'
end
end
private
# Only allow a trusted parameter "white list" through.
def test_params
params.require(:test).permit(
:date,
:start_time,
:description,
:machine,
:location,
:feeder_screw_diameter,
:notes,
:user_id,
:tool_ids => [],
:powder_ids => []
)
end
Log output when submitting:
Started POST "/tests" for 127.0.0.1 at 2016-05-08 13:24:52 +0100
Processing by TestsController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"WKw+tQ1WKyxW7XZWCDvbvShCKnZ7iMY597P8eDGIvZEyis4ks7Mf4Lcu4vCf7q+fwtsReocmAlMGUrrhI4SgdQ==",
"test"=>{"start_time(1i)"=>"2016",
"start_time(2i)"=>"5",
"start_time(3i)"=>"8",
"start_time(4i)"=>"13",
"start_time(5i)"=>"23",
"description"=>"Test",
"machine"=>"Some machine",
"location"=>"Some Place",
"feeder_screw_diameter"=>"15",
"tool_ids"=>"21",
"powder_ids"=>["", "3"],
"user_id"=>"1",
"date"=>"11-05-2016",
"notes"=>"Some Notes"},
"button"=>""}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Completed 500 Internal Server Error in 14ms (ActiveRecord: 0.4ms)
** [Airbrake] Notice was not sent due to configuration:
Environment Monitored? false
API key set? true
ActionController::UnpermittedParameters (found unpermitted parameter: tool_ids):
app/controllers/tests_controller.rb:201:in `test_params'
app/controllers/tests_controller.rb:70:in `create'
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.0ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.7ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (12.9ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (7.9ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.2ms)
Rendered /home/me/.rvm/gems/ruby-2.1.7/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (16.1ms)
Many thanks for any help!

uninitialized constant ApplicationController::PermittedParams strong parameters

Don't know where i'm getting wrong, i have searched a lot googling and also in SO but i don't understand what i am doing wrong.
My Application Controller
class ApplicationController < ActionController::Base
helper_method :clipboard, :current_user, :signed_in?, :permitted_params
def permitted_params
#permitted_params ||= PermittedParams.new(params, current_user)
end
My Model Permitted_Param.rb
class PermittedParams < Struct.new(:params, :current_user)
%w{folder group share_link user user_file}.each do |model_name|
define_method model_name do
params.require(model_name.to_sym).permit(*send("#{model_name}_attributes"))
end
end
def folder_attributes
[:name]
end
def group_attributes
[:name]
end
def share_link_attributes
[:emails, :link_expires_at, :message]
end
def user_attributes
if current_user && current_user.member_of_admins?
[:name, :email, :password, :password_confirmation, { :group_ids => [] }]
else
[:name, :email, :password, :password_confirmation]
end
end
def user_file_attributes
[:attachment, :attachment_file_name]
end
end
Log
Started GET "/" for 127.0.0.1 at 2015-04-16 19:37:02 +0530
ActiveRecord::SchemaMigration Load (0.6ms) SELECT
"schema_migrations".* FROM "schema_migrations" Processing by
FoldersController#index as HTML User Load (0.5ms) SELECT "users".*
FROM "users" WHERE "users"."is_admin" = ? LIMIT 1 [["is_admin", "t"]]
Redirected to http://localhost:3000/admins/new Filter chain halted as
:require_admin_in_system rendered or redirected Completed 302 Found in
207ms (ActiveRecord: 1.0ms) Started GET "/admins/new" for 127.0.0.1 at
2015-04-16 19:37:03 +0530 Processing by AdminsController#new as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE
"users"."is_admin" = ? LIMIT 1 [["is_admin", "t"]] Rendered
admins/new.html.erb within layouts/application (331.3ms) User Load
(0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL
LIMIT 1 Rendered shared/_header.html.erb (21.3ms) CACHE (0.1ms)
SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Rendered shared/_menu.html.erb (8.4ms) Rendered
shared/_footer.html.erb (0.8ms) Completed 200 OK in 1789ms (Views:
1707.5ms | ActiveRecord:
1.7ms)
Started POST "/admins" for 127.0.0.1 at 2015-04-16 19:37:19 +0530 Processing by AdminsController#create as HTML Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"5VPDMdM6Cny63T00tcgU55ukkDD9XChTQwWjAJ7IUZ0ELh6D5c7UhbpbOKdQ3atdaNIaBVk5AxctcC0j09pcvQ==",
"user"=>{"name"=>"ChiragArya", "email"=>"edwardmaya008#gmail.com",
"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"},
"commit"=>"Create admin account"} User Load (0.4ms) SELECT
"users".* FROM "users" WHERE "users"."is_admin" = ? LIMIT 1
[["is_admin", "t"]] Completed 500 Internal Server Error in 26ms
(ActiveRecord: 0.4ms)
NameError (uninitialized constant ApplicationController::PermittedParams):
app/controllers/application_controller.rb:26:in permitted_params'
app/controllers/admins_controller.rb:10:in
Rendered /home/chirag/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb
(54.9ms) Rendered
/home/chirag/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (35.3ms) Rendered
/home/chirag/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
(10.4ms) Rendered
/home/chirag/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb
within rescues/layout (227.5ms)
I got the same problem and i resolved that after renaming my strong parameter function name to controllername_params
I don't know where is the mention but i'd love to know that .

How to update a model record? [Rails 4]

I need to update my Pack model in my Rails application, but every time I submit the form, nothing happens. Here's the code:
packs_controller.rb
def edit
#pack = Pack.find(params[:id])
end
def update
#pack = Pack.find(params[:id])
if #pack.update_attributes(pack_params)
flash[:success] = "Update successful!"
redirect_to '/packs'
else
render 'edit'
end
end
private
def pack_params
params.require(:pack).permit(:amount)
end
_edit_packs.html.haml
= form_for(#pack) do |f|
.form-group
= f.label :amount
= f.text_field :amount, :autofocus => true, class: 'form-control'
= f.submit 'Submit', :class => 'button right'
Any ideas?
EDIT
Here is the log when pressing submit:
Started PATCH "/packs/11" for 127.0.0.1 at 2014-06-13 19:27:12 +0200
Started PATCH "/packs/11" for 127.0.0.1 at 2014-06-13 19:27:12 +0200
Processing by PacksController#update as HTML
Processing by PacksController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oa20eUeZPxbV+mX0mQyDyFibwWCnOlrtP/9uoKq2HU0=", "pack"=>{"amount"=>"1"}, "commit"=>"Submit", "id"=>"11"}
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oa20eUeZPxbV+mX0mQyDyFibwWCnOlrtP/9uoKq2HU0=", "pack"=>{"amount"=>"1"}, "commit"=>"Submit", "id"=>"11"}
Pack Load (0.1ms) SELECT "packs".* FROM "packs" WHERE "packs"."id" = ? ORDER BY created_on DESC LIMIT 1 [["id", 11]]
Pack Load (0.1ms) SELECT "packs".* FROM "packs" WHERE "packs"."id" = ? ORDER BY created_on DESC LIMIT 1 [["id", 11]]
(0.1ms) begin transaction
(0.1ms) begin transaction
Pack Exists (0.1ms) SELECT 1 AS one FROM "packs" WHERE ("packs"."created_on" = '2014-06-13' AND "packs"."id" != 11) LIMIT 1
Pack Exists (0.1ms) SELECT 1 AS one FROM "packs" WHERE ("packs"."created_on" = '2014-06-13' AND "packs"."id" != 11) LIMIT 1
(0.0ms) rollback transaction
(0.0ms) rollback transaction
Rendered packs/_edit_packs.html.haml (1.8ms)
Rendered packs/_edit_packs.html.haml (1.8ms)
Rendered packs/edit.html.haml within layouts/application (2.5ms)
Rendered packs/edit.html.haml within layouts/application (2.5ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1
Rendered layouts/_navigation_links.html.erb (1.2ms)
Rendered layouts/_navigation_links.html.erb (1.2ms)
Rendered layouts/_navigation.html.haml (1.9ms)
Rendered layouts/_navigation.html.haml (1.9ms)
Rendered layouts/_messages.html.haml (0.1ms)
Rendered layouts/_messages.html.haml (0.1ms)
Completed 200 OK in 28ms (Views: 22.0ms | ActiveRecord: 0.6ms)
Completed 200 OK in 28ms (Views: 22.0ms | ActiveRecord: 0.6ms)
EDIT 2
After having looked through some of the comments, and thinking about the problem, it seems like there's a problem with my uniqueness validation on the :created_on field, which stores the date the record was created on.
EDIT 3
Confirmed: :created_on is the root of the problem! I have a validation that enforces the uniqueness of :created_on. When I remove it, the form works. Here is my model:
pack.rb
class Pack < ActiveRecord::Base
belongs_to :user
default_scope -> { order('created_on DESC') }
scope :today, -> { where(:created_at => (Time.now.beginning_of_day..Time.now)) }
scope :week, -> { where(:created_at => (Time.now.beginning_of_week..Time.now))}
scope :month, -> { where(:created_at => (Time.now.beginning_of_month..Time.now))}
scope :year, -> { where(:created_at => (Time.now.beginning_of_year..Time.now))}
validates :user_id, presence: true
validates :created_on, uniqueness: true
validates :amount, presence: true, length: { maximum: 1 }
end
Any suggestions on how to get around this? Should I start a new question?
Based on your logs, it looks like you have multiple packs in your database that were created_on is equal to '2014-06-13' which will cause the created_on uniqueness validation to fail.
Check this in the rails console:
Pack.where(created_on: '2014-06-13')
If there is more than one, delete the extras and it should work.
If you are trying to limit a pack to one per user per day you need to add a scope option to the created on validation:
validates :created_on, uniqueness: true, scope: user

Resources