How to update a model record? [Rails 4] - ruby-on-rails

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

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

Rails does not create associated model

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.

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.

RoR - ActiveAdmin Impossible to create a new product with nested form

I am new to rails and I'm trying to customize ActiveAdmin.
My app has 3 models: User (which has many products), Product (which has many prices) and Price. I am trying to customize ActiveAdmin with a nested form to be able to create/update a product directly with its prices.
Although the update works perfectly (updating product and even adding a new price), the create action doesn't work. I get "rollback" in the console but no specific error message.
Can you tell me what I'm doing wrong?
# app/admin/products.rb
ActiveAdmin.register Product do
form do |f|
f.semantic_errors
f.inputs do
f.input :name
f.input :size
end
f.inputs "Prices" do
f.has_many :prices do |price|
price.input :value
price.input :currency, :collection => ["dollars", "euros", "pounds"]
end
end
f.actions
end
permit_params :name, :size, :user_id, prices_attributes: [:id, :currency, :value, :product_id, :_edit, :_update, :_new, :_create]
I have also put "accepts_nested_attributes_for :prices" in app/models/product.rb.
The logs form the console
Started POST "/admin/products" for 127.0.0.1 at 2018-03-28 14:46:05 +0200
Processing by Admin::ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"W9OJHqyFzXREfi4/DuBN1xnf0KIhAjJDfGsZjQqvGJ7BZOb11fVAz78djOf1k3XZdmpJxuPYinYi6Knu2agvnQ==", "product"=>{"name"=>"Shorts", "size"=>"XL", "prices_attributes"=>{"0"=>{"value"=>"40", "currency"=>"euros"}}}, "commit"=>"Create Product"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
AdminUser Load (0.4ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1 ORDER BY "admin_users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
(0.3ms) ROLLBACK
Rendering /Users/alex/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/activeadmin-1.2.1/app/views/active_admin/resource/new.html.arb
Rendered /Users/alex/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/activeadmin-1.2.1/app/views/active_admin/resource/new.html.arb (100.1ms)
Completed 200 OK in 248ms (Views: 132.6ms | ActiveRecord: 1.9ms)
Thank you very much for you help.

rails has_one belongs to form submission error

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. :-)

Resources