rails has_one belongs to form submission error - ruby-on-rails

I have two models and i'm trying to integrate it, i can bring form another model, problem is while submission , id is being updated to null
orbituary model:
class Orbituarysite < ActiveRecord::Base
attr_accessible :birth_place, :death_place, :dob, :dod, :name, :living_place, :orbiturerimage, :salutation, :user_id
belongs_to :user
mount_uploader :orbiturerimage, OrbiturerUploader
has_one :notice_display
end
Notice model
class NoticeDisplay < ActiveRecord::Base
attr_accessible :message, :notice_type, :orbituarysite_id, :posted_by, :notice_event_places_attributes, :notice_event_contacts_attributes
belongs_to :orbituarysite
end
orbituary controller:
def show
#orbituarysite = Orbituarysite.find(params[:id])
if #orbituarysite.notice_display.nil?
#notice_display = #orbituarysite.build_notice_display
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: #orbituarysite }
end
end
in orbituary sites show view:
<% if #orbituarysite.notice_display.nil? %>
<%= render 'notice_displays/form' , :remote => true %>
<% end %>
while i submit the form i get the following problem, i.e, aftter submission i redirect it to orbituary sites page so i get this in server,
Started GET "/orbituarysites/1" for 127.0.0.1 at 2013-09-05 08:58:45 +0530
Processing by OrbituarysitesController#show as HTML
Parameters: {"id"=>"1"}
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Orbituarysite Load (1.8ms) SELECT "orbituarysites".* FROM "orbituarysites" WHERE "orbituarysites"."id" = $1 LIMIT 1 [["id", "1"]]
NoticeDisplay Load (0.8ms) SELECT "notice_displays".* FROM "notice_displays" WHERE "notice_displays"."orbituarysite_id" = 1 LIMIT 1
History Load (0.9ms) SELECT "histories".* FROM "histories" WHERE "histories"."orbituarysite_id" = 1 LIMIT 1
(0.5ms) BEGIN
(0.9ms) UPDATE "histories" SET "orbituarysite_id" = NULL, "updated_at" = '2013-09-05 03:28:46.214455' WHERE "histories"."id" = 2
(25.0ms) COMMIT
Rendered histories/_form.html.erb (125.2ms)
Rendered memories/_form.html.erb (9.1ms)
Rendered condolences/_form.html.erb (14.4ms)
Rendered orbiturer_share_images/_form.html.erb (6.2ms)
Rendered orbituarysites/show.html.erb within layouts/application (162.6ms)
Rendered orbituarysites/_form.html.erb (26.4ms)
Completed 200 OK in 944ms (Views: 504.5ms | ActiveRecord: 64.5ms)
how to change this because get false in
<% if #orbituarysite.notice_display.nil? %>
but in console i get true when it is nil and false when there is content
Please help me to solve this

.nil? does not always guarantee truthiness. Use #orbituarysite.notice_display.present?
Essentially, all nil's return true because in ruby all things are truthy except false and nil.
So you're code will always return TRUE because it will return nil. :-)

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

How to set a form for nested attributes with collection selection?

I am trying to configure a form for nested attributes with a selector on RoR, but it seems I am doing it wrong.
I am trying to create a new affaire with nested_attributes contributions.
Each contribution belongs to a skill which needs to be defined.
As there is a limited number of possible skills, I would like to have a selector in my form to select the contribution_skill from a list.
EDIT : I finally made it save the affaire with contributions by setting all the contribution attributes (I used the defaut set in the model definition).
But I don't always want these attributes to be defined, so it is still not the solution.
I add that there is no presence validation on these attributes.
Anyone knows how to save a nested_attribute without all nested_attribute_attributes defined ?
Here is the models definitions :
class Affaire < ApplicationRecord
has_many :contributions
accepts_nested_attributes_for :contributions
end
class Skill < ApplicationRecord
has_many :contributions
end
class Contribution < ApplicationRecord
belongs_to :skill
belongs_to :affaire
end
Controller definition :
def new
#affaire = Affaire.new
2.times {#affaire.contributions.build}
end
def create
#affaire = Affaire.new(affaire_params)
#affaire.save
redirect_to #affaire
end
private
def affaire_params
params.require(:affaire).
permit(:nam, contributions_attributes: [:id, :skill_id])
end
View definition :
<%= form_with model: #affaire do |form| %>
<%= form.label :name, "Name of Affaire" %>
<%= form.text_field :name %>
<%= form.fields_for :contributions do |ff| %>
<%= ff.label :skill_id, "Contribution" %>
<%= ff.collection_select(:skill_id, Skill.all, :id, :name) %>
<% end %>
<%= form.submit "Create affaire" %>
I am expecting to get my affaire created with my contribution and the contribution to have its skill set.
Unfortunately, it goes wrong.
Here iswhat I got in the rails server console :
Started GET "/affaires/new" for ::1 at 2019-09-04 21:06:41 +0200
Processing by AffairesController#new as HTML
Rendering affaires/new.html.erb within layouts/application
Skill Load (0.4ms) SELECT "skills".* FROM "skills"
↳ app/views/affaires/new.html.erb:30
CACHE Skill Load (0.0ms) SELECT "skills".* FROM "skills"
↳ app/views/affaires/new.html.erb:30
Rendered affaires/new.html.erb within layouts/application (20.9ms)
Completed 200 OK in 105ms (Views: 70.3ms | ActiveRecord: 2.2ms)
Started POST "/affaires" for ::1 at 2019-09-04 21:06:48 +0200
Processing by AffairesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"GCc2wX2C7mWn77eksjdhDp5i1lFoUc2L3MLkOIXmWhavNdxwIynpNTVaRmbrvkKNdRtQxqoXjaInI2MaJtvvFA==", "affaire"=>{"name"=>"test", "contributions_attributes"=>{"0"=>{"skill_id"=>"3"}, "1"=>{"skill_id"=>"1"}}}} (0.3ms) BEGIN
↳ app/controllers/affaires_controller.rb:20
Skill Load (0.3ms) SELECT "skills".* FROM "skills" WHERE "skills"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/affaires_controller.rb:20
Skill Load (0.3ms) SELECT "skills".* FROM "skills" WHERE "skills"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/affaires_controller.rb:20
(0.2ms) ROLLBACK
↳ app/controllers/affaires_controller.rb:20
Redirected to http://localhost:3000/affaires
Completed 200 OK in 27ms (ActiveRecord: 2.8ms)
I can't see where is the problem.
Parameters seems ok to me if I refer to rails documentation. I don't get why it rolls back.
Thanks for your help

uninitialized constant Degree(error)

I am getting the error uninitialized constant Degree. I have a column in database with column name type. When i give data to that field and save, the data i gave is getting saved in database but error message is displayed after that and i am not able to reload that page.
Controller code
class ProfileController < ApplicationController
before_action :set_user, only: %i[index update_profile]
def index; end
def update_profile
if #user.update(user_params)
redirect_to profile_index_path, notice: 'Profile was successfully updated.'
else
render :index
end
end
private
def set_user
#user = User.find(current_user.id)
#user.education || #user.build_education
end
def user_params
params.require(:user).permit(:name, education_attributes: %i[id type name issue_institute education_status])
end
end
education.rb
class Education < ApplicationRecord
belongs_to :user
validates_presence_of :user_id
end
user.rb
class User < ApplicationRecord
has_one :education, dependent: :destroy
accepts_nested_attributes_for :education
end
View code
<%= form_for(#user, url: {action: 'update_profile'}, html: {class: 'm-form m-form--fit m-form--label-align-right'}) do |f| %>
<%= f.fields_for :education, #user.education do |e| %>
<%= e.select :type, options_for_select(%w(Degree Certification), params[:type]), prompt: 'Degree/Certification', class: 'form-control m-input' %>
<%= end %>
<%= f.submit 'Save Changes'%>
<%= end %>
Terminal Log when i save that field
Started PATCH "/profile/update_profile" for 127.0.0.1 at 2018-05-30 09:04:37 +0530
Processing by ProfileController#update_profile as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9QiEdSxqwkhHqZHiraiQjJcUvUS+oJknYjYaxWUSQrh+je0ASeYQvs//Z+p+oZkOqyAiwxc3nsxp/iohO9B1BA==", "user"=>{"name"=>"Admin", "email"=>"admin#gmail.com", "address_attributes"=>{"area"=>"5, nehru Street", "city"=>"pune", "state"=>"mumbai", "country"=>"india", "postcode"=>"626781", "id"=>"1"}, "education_attributes"=>{"type"=>"Degree", "name"=>"ffgxh", "issue_institute"=>"", "education_status"=>"", "id"=>"1"}, "fee_attributes"=>{"fee_hour"=>"", "fee_month"=>"", "id"=>"1"}}, "commit"=>"Save Changes"}
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Address Load (0.2ms) SELECT `addresses`.* FROM `addresses` WHERE `addresses`.`user_id` = 2 LIMIT 1
Fee Load (0.2ms) SELECT `fees`.* FROM `fees` WHERE `fees`.`user_id` = 2 LIMIT 1
Education Load (0.2ms) SELECT `educations`.* FROM `educations` WHERE `educations`.`user_id` = 2 LIMIT 1
Unpermitted parameter: :email
(0.2ms) BEGIN
SQL (0.4ms) UPDATE `educations` SET `type` = 'Degree', `updated_at` = '2018-05-30 03:34:37' WHERE `educations`.`id` = 1
(5.3ms) COMMIT
Redirected to http://localhost:3000/profile
Completed 302 Found in 19ms (ActiveRecord: 7.1ms)
Started GET "/profile" for 127.0.0.1 at 2018-05-30 09:04:37 +0530
Processing by ProfileController#index as HTML
User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Address Load (0.4ms) SELECT `addresses`.* FROM `addresses` WHERE `addresses`.`user_id` = 2 LIMIT 1
Fee Load (0.3ms) SELECT `fees`.* FROM `fees` WHERE `fees`.`user_id` = 2 LIMIT 1
Education Load (0.8ms) SELECT `educations`.* FROM `educations` WHERE `educations`.`user_id` = 2 LIMIT 1
Completed 401 Unauthorized in 12ms (ActiveRecord: 2.4ms)
NameError - uninitialized constant Degree:
app/controllers/profile_controller.rb:41:in `set_user'
Data gets saved but i have error page after that. Can someone help me with it? Thanks in advance.
I am posting my comment as an answer so that anyone can reference that in future:
type is a reserved keyword for AR. Check list of reserve active record keywords from here. Change the column name. It will resolve the error.

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!

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