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.
Related
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
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.
I have task which has many appointments. When creating a new task, I have only one appointment (Because appointment is only created one at a time). I have no problem with new and create action, appointment will be validated save to the db. THE PROBLEM IS when I edit a task, the child form (appointment) is not validating nor updating.
Strong params in task controller:
def task_params
params.require(:task).permit(:category_id, :subcategory_id, :title, :description, :pay_offer, :is_pay_per_hour, :county_id, :area_id,
appointments_attributes: [:id, :start_date, :start_time, :duration])
end
Task:
has_many :appointments, :dependent => :destroy
accepts_nested_attributes_for :appointments
Appointment:
belongs_to :task
Actions in task controller:
def new
#task = current_user.task_posts.build
#task.appointments.build
end
def create
#task = current_user.task_posts.build(task_params)
if #task.save
flash[:success] = "Micropost created!"
redirect_to #current_user
else
render 'new'
end
end
def edit
#task = Task.find(params[:id])
#task.county_id = #task.county.id
#task.category_id = #task.category.id
#task.appointments.first
end
def update
#task = Task.find(params[:id])
if #task.update_attributes(task_params)
flash[:success] = "Task updated"
redirect_to #task
else
render 'edit'
end
end
Edit and new template:
<%= simple_form_for #task, html: {class: 'form-horizontal'}, wrapper: :horizontal_input_group do |f| %>
.....some fields of #task
<% f.simple_fields_for :appointments do |b| %>
<%= b.input :start_date, label: "Start date", wrapper: :horizontal_input_group do %>
<%= b.input_field :start_date, placeholder: 'Set ', class: "form-control date start" %><span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
<% end %>
<%= b.input :start_time, label: "Start time", wrapper: :horizontal_input_group do %>
<%= b.input_field :start_time, placeholder: 'Starting time at', as: :string, class: "form-control time start" %><span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>
<% end %>
<%= b.input :duration, label: "Duration", wrapper: :horizontal_input_group do %>
<%= b.input_field :duration, placeholder: 'Duration', as: :integer, class: "form-control", min: "1", max: "8"%>
<span class="input-group-addon" id="hour-addon">Hour(s)</span>
<% end %>
<% end %>
SOME SCENARIO:
Suppose the date time is 28 april 2015, 7:00 am.
If I go to edit form and change the start date and time to 2 May 2015, 2:00 am, this is what I will get in console:
Started PATCH "/tasks/121" for ::1 at 2015-04-21 11:19:20 +0100
Processing by TasksController#update as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"+Qfn0bsSEHWXxnHFAQCpr/rAL8OkY
ichj2FDfAXF8siWu3/NsZlj2O3N5PptcCqy8PyhH3/mIT4/ZOvozoh9hw==", "task"=>{"category
_id"=>"1", "subcategory_id"=>"2", "title"=>"ssdsdsssdasdsdddddddddd", "descripti
on"=>"sdsdsssssssssssssssssssssssss", "county_id"=>"15", "area_id"=>"659", "is_p
ay_per_hour"=>"0", "pay_offer"=>"29", "appointments_attributes"=>{"0"=>{"start_d
ate"=>"2/5/2015", "start_time"=>"02:00 AM", "duration"=>"0", "id"=>"134"}}}, "co
mmit"=>"Update Task", "id"=>"121"}
Task Load (1.0ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`id` = 121 OR
DER BY created_at DESC LIMIT 1
(0.0ms) BEGIN
Appointment Load (1.0ms) SELECT `appointments`.* FROM `appointments` WHERE `a
ppointments`.`task_id` = 121 AND `appointments`.`id` = 134
(0.0ms) COMMIT
It is still 28 april 2015, 7:00 am.
COMPLETE CONSOLE LOG:
Started PATCH "/tasks/131" for ::1 at 2015-04-21 11:41:49 +0100
Processing by TasksController#update as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"iP++ZG5VpAevK2awi6vaoixVDA8zc
BI7b0IducbwmvvnQyZ4ZN7XqtUg84/n21m/JmmC0+j0FCTfR7UtDb0VtA==", "task"=>{"category
_id"=>"1", "subcategory_id"=>"3", "title"=>"dddddddddddddddddddddddddddddd", "de
scription"=>"ddddddddddddddddddddddddddddddddddddddddddd", "county_id"=>"17", "a
rea_id"=>"723", "is_pay_per_hour"=>"0", "pay_offer"=>"22", "appointments_attribu
tes"=>{"0"=>{"start_date"=>"2/5/2015", "start_time"=>"02:00 AM", "duration"=>"0"
, "id"=>"145"}}}, "commit"=>"Update Task", "id"=>"131"}
Task Load (0.0ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`id` = 131 OR
DER BY created_at DESC LIMIT 1
(0.0ms) BEGIN
Appointment Load (0.0ms) SELECT `appointments`.* FROM `appointments` WHERE `a
ppointments`.`task_id` = 131 AND `appointments`.`id` = 145
(0.0ms) COMMIT
Redirected to http://localhost:3000/tasks/131
Completed 302 Found in 11ms (ActiveRecord: 0.0ms)
Started GET "/tasks/131" for ::1 at 2015-04-21 11:41:49 +0100
Processing by TasksController#show as HTML
Parameters: {"id"=>"131"}
Task Load (0.0ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`id` = 131 OR
DER BY created_at DESC LIMIT 1
Response Load (0.0ms) SELECT `responses`.* FROM `responses` WHERE `responses`
.`task_id` = 131 ORDER BY created_at DESC
User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT
1
Area Load (0.0ms) SELECT `areas`.* FROM `areas` WHERE `areas`.`id` = 723 LIM
IT 1
County Load (0.0ms) SELECT `counties`.* FROM `counties` WHERE `counties`.`id
` = 17 LIMIT 1
Subcategory Load (0.0ms) SELECT `subcategories`.* FROM `subcategories` WHERE
`subcategories`.`id` = 3 LIMIT 1
Category Load (0.0ms) SELECT `categories`.* FROM `categories` WHERE `categor
ies`.`id` = 1 LIMIT 1
Rendered tasks/_task_info.html.erb (11.0ms)
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
[["id", 1]]
Rendered tasks/_question_negotiation_form.html.erb (67.0ms)
Rendered collection (0.0ms)
Appointment Load (1.0ms) SELECT `appointments`.* FROM `appointments` WHERE `
appointments`.`task_id` = 131 ORDER BY `appointments`.`id` ASC LIMIT 1
CACHE (0.0ms) SELECT `appointments`.* FROM `appointments` WHERE `appointment
s`.`task_id` = 131 ORDER BY `appointments`.`id` ASC LIMIT 1 [["task_id", 131]]
CACHE (0.0ms) SELECT `appointments`.* FROM `appointments` WHERE `appointment
s`.`task_id` = 131 ORDER BY `appointments`.`id` ASC LIMIT 1 [["task_id", 131]]
CACHE (0.0ms) SELECT `appointments`.* FROM `appointments` WHERE `appointment
s`.`task_id` = 131 ORDER BY `appointments`.`id` ASC LIMIT 1 [["task_id", 131]]
Rendered tasks/_first_appointment_info.html.erb (6.0ms)
Rendered tasks/_appointed_worker.html.erb (9.0ms)
Rendered tasks/show.html.erb within layouts/application (96.1ms)
Rendered layouts/_header.html.erb (4.0ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 149ms (Views: 143.1ms | ActiveRecord: 1.0ms)
Started GET "/assets/application-8636d652720c67486ff35a011cfcda8b.css" for ::1 a
t 2015-04-21 11:41:49 +0100
Started GET "/assets/application-fb8ea68f36532aeef58f0517a0a44ab7.js" for ::1 at
2015-04-21 11:41:49 +0100
Can some one help me please?
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
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. :-)