I have 2 associated models and am trying to create the child from the parent's controller:
class Purchase < ActiveRecord::Base
has_many :comments, as: :commentable, dependent: :destroy
accepts_nested_attributes_for :comments, reject_if: :all_blank, allow_destroy: true
end
class Comment < ActiveRecord::Base
belongs_to :employee
belongs_to :commentable, polymorphic: true
validates_presence_of :body, :employee_id, :commentable_id, :commentable_type
end
In my controller I accept the params for comment:
def create
#purchase = Purchase.new(purchase_params)
if #purchase[:discount] && #purchase[:discount] > 0
#purchase[:discount] = #purchase[:discount].round(3)
end
if #purchase.save
render json: #purchase, status: :created
else
p "errors", #purchase.errors
render json: #purchase.errors.full_messages, status: :unprocessable_entity
end
end
private
def purchase_params
params.require(:purchase).permit(
:sale_type, :weeks, :weekly_cost, :date, :discount, :client_id, :id, :created_at, :updated_at, :employee_id, :consultation_id, :program_id, :purchaseable_type, :purchaseable_id,
comments_attributes: [:body, :id, :employee_id, :commentable_type]
)
end
When I attempt to create the purchase with the following params, I get the error:
purchase = {
client_id: client.id,
weeks: 5,
weekly_cost: 295,
comments_attributes: [{
employee_id: employee.id,
body: "This is a test",
commentable_type: "Purchase"
}]
}
#<ActiveModel::Errors:0x00007fb0ef3849e0 #base=#<Purchase id: nil, weeks: 5, weekly_cost: 295.0, created_at: nil, updated_at: nil, client_id: 18, discount: nil, employee_id: nil, comment: nil, referral_used: false, deleted_at: nil, date: nil, sale_type: nil, purchaseable_type: nil, purchaseable_id: nil, program_id: nil>, #messages={:"comments.commentable_id"=>["can't be blank"]}, #details={:"comments.commentable_id"=>[{:error=>:blank}]}>
There's no way to know the commentable_id before saving the purchase. What am I missing?
Related
Heya im pulling my hair out right now
class Referal < ApplicationRecord
validates :pax, :presence => true
validates :customer_email, presence: true
default_scope -> { order('created_at DESC') }
self.implicit_order_column = "created_at"
belongs_to :referer, class_name: "User"
belongs_to :customer, class_name: "User"
belongs_to :business
<Referal:0x000055f8a468b058
id: nil,
state: nil,
handle: nil,
sec_code: nil,
pax: nil,
booking_date_time: nil,
business_id: "224cd62b-3d29-41ca-a1be-f308815514b2",
customer_id: nil,
referer_id: "cdfb1861-d5e4-4650-9783-4189cffde6bd",
customer_email: nil,
customer_mobile: nil,
customer_last_name: nil,
customer_first_name: nil,
created_at: nil,
updated_at: nil>
x.valid?
=> true
i tried multiple ways but it seems since i have multiple FK's in the model it only validates the ft for Business and Referer
how do i enforce the validator for additional fields? thanks
I use rolify gem with devise for AdminUser
my Roles table
class RolifyCreateRoles < ActiveRecord::Migration
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:admin_users_roles, :id => false) do |t|
t.references :admin_user
t.references :role
end
add_index(:roles, :name)
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:admin_users_roles, [ :admin_user_id, :role_id ])
end
end
model 'Role'
class Role < ActiveRecord::Base
has_and_belongs_to_many :admin_users, :join_table => :admin_users_roles
belongs_to :resource,
:polymorphic => true
validates :resource_type,
:inclusion => { :in => Rolify.resource_types },
:allow_nil => true
scopify
end
my issue is when i want to get users witch belong to role it gives empty array instead of my adminuser object
u = AdminUser.first
u.add_role(:admin)
u.roles => #<Role id: 1, name: "admin", admin_user_id: 1, resource_id: nil, resource_type: nil, created_at: "2016-06-16 15:03:33", updated_at: "2016-06-17 09:04:30">
and when i do
Role.first=> #<Role id: 1, name: "admin", admin_user_id: 1, resource_id: nil, resource_type: nil, created_at: "2016-06-16 15:03:33", updated_at: "2016-06-17 09:29:32">
Role.first.admin_users => []
To check if a user has a global role:
user = User.find(1)
user.add_role :admin # sets a global role
user.has_role? :admin
=> true
Or to check at instance level In your case
u = AdminUser.first
u.add_role(:admin)
> Role.first=> #<Role id: 1, name: "admin", admin_user_id: 1,
> resource_id: nil, resource_type: nil, created_at: "2016-06-16
> 15:03:33", updated_at: "2016-06-17 09:29:32">
Instead of doing this => Role.first.admin_users => []
Try
u = AdminUser.first
u.roles
Rolify has a pretty clear documentation
Rolify
oh i fixed it by changing relation in my admin_user model
from has_many to has_and_belongs_to_many :roles
When I attempt to rake db:seed, I get the error above, in my rails console :
=> #<ActiveRecord::Relation [#<Product id: 16, name: nil, price: nil, active: true, description: nil, image_url: nil, professor: nil, created_at: "2015-04-24 06:59:58", updated_at: "2015-04-24 06:59:58">, #<Product id: 17, name: nil, price: nil, active: true, description: nil, image_url: nil, professor: nil, created_at: "2015-04-24 06:59:58", updated_at: "2015-04-24 06:59:58">, #<Product id: 18, name: nil, price: nil, active: true, description: nil, image_url: nil, professor: nil, created_at: "2015-04-24 06:59:58", updated_at: "2015-04-24 06:59:58">]>
Here's my seeds.rb :
Product.delete_all
Product.create( name: 'Montages simples ikebana en chocolat',
description:
%{
Créez des montages commerciaux simple et rapide pour mettre en valeur votre vitrine.
},
image_url: 'IMG_4543.JPG',
price: 9.00,
professor: 'avec Jérémy Fages', active: true)
Product.create( name: 'Example2',
description:
%{
Miam miam.
},
image_url: 'miam.jpg',
price: 'gratuit',
professor: 'avec Jérémy Fages', active: true)
Here's my ***********_create_products.rb :
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.decimal :price, precision: 12, scale: 3
t.boolean :active
t.text :description
t.string :image_url
t.text :professor
t.timestamps
end
end
end
and my Model/products.rb :
class Product < ActiveRecord::Base
has_many :order_items
default_scope { where(active: true) }
end
I tried the commands rake db:drop rake db:create rake db:migrate...
Here is my Model/Order_item.rb :
class OrderItem < ActiveRecord::Base
belongs_to :product
belongs_to :order
validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
validate :product_present
validate :order_present
before_save :finalize
def unit_price
if persisted?
self[:unit_price]
else
product.price
end
end
def total_price
unit_price * quantity
end
private
def product_present
if product.nil?
errors.add(:product, "is not valid or is not active.")
end
end
def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end
def finalize
self[:unit_price] = unit_price
self[:total_price] = quantity * self[:unit_price]
end
end
About the code , it runs on an application that uses sqlite3 . The problem appears on my other application with mysql2 .
I am submitting a form into a CorporateContactFormsController. I can see the parameters are being passed but they are not being added to the instantiated class.
def create
#contact_form = CorporateContactForm.new(corporate_contact_form_params)
raise
end
private
def corporate_contact_form_params
params.require(:corporate_contact_form).permit(:firstname, :surname, :contact_number, :email, :company_name, :method_of_payment, :number_of_employees, :comments, :contact_type)
end
This is from better-errors gem
>> corporate_contact_form_params
=> {"firstname"=>"qwertyui", "surname"=>"wertyuio", "contact_number"=>"wertyuio", "email"=>"qwdqwd#iugh.com", "company_name"=>"wqedfwefwef", "method_of_payment"=>"Other", "number_of_employees"=>"1-50", "comments"=>"qwdqwdqwdqwdqwdqwdwqd", "contact_type"=>"employee"}
>> #contact_form = CorporateContactForm.new(corporate_contact_form_params)
=> #<CorporateContactForm id: nil, contact_type: nil, firstname: nil, surname: nil, contact_number: nil, email: nil, company_name: nil, company_website: nil, position_in_company: nil, location: nil, number_of_employees: nil, method_of_payment: nil, comments: nil, created_at: nil, updated_at: nil>
Why aren't the parameters populating the new instance of the class?
I am using rails 4.0
update
model
class CorporateContactForm < ActiveRecord::Base
EMPLOYEE = 'employee'
EMPLOYER = 'employer'
CONTACT_TYPE = [EMPLOYEE, EMPLOYER]
ONE_TO_FIFITY = "1-50"
FIFTY_TO_ONEHUNDRED = "50-100"
ONEHUNDRED_OR_MORE = "100+"
EMPLOYEE_COUNT = [ONE_TO_FIFITY, FIFTY_TO_ONEHUNDRED, ONEHUNDRED_OR_MORE]
OTHER = "Other"
COMPANY = "Company funded"
METHOD_OF_PAYMENT = [COMPANY, OTHER]
validates :contact_type, inclusion: CONTACT_TYPE, presence: true
validates :number_of_employees, inclusion: EMPLOYEE_COUNT, presence: true
validates :firstname, presence: :true
validates :email, presence: :true
validates :company_name, presence: :true
validates :email, presence: :true
validate :blanks_to_nils
private
def blanks_to_nils
blank_to_nil :surname
blank_to_nil :contact_number
blank_to_nil :position_in_company
blank_to_nil :location
blank_to_nil :method_of_payment
blank_to_nil :comments
end
let say that I have two class
class User
attr_accessible :name
has_one :address
validates :name, :presence => true
validates_associated :address
end
class Address
attr_accessible :country, :user_id
belongs_to :user
validates :country, :presence => true
validates :user, :presence => true
end
Now when i try to create invalid Address then it fails(which is good)
a = Address.new
a.valid? #=> false
But when i build User with invalid Address then it pass(which is bad)
u = User.first
u.build_address
u.valid? #=> true
u.save #=> true
Due to this User has Address with country => nil.
How can i tell Rails to not save Address if its invalid?
FIXED: I fixed this by adding follow line to the code. Thank you everyone.
validates_associated :address, :if => :address
class User
attr_accessible :name
has_one :address, :validate => true
validates :name, :presence => true
validates_associated :address
end
You need to also validate that an Address is actually present for User:
class User < ActiveRecord::Base
validates :address, :associated => true, :presence => true
end
With that in place, I get:
>> u = User.first
=> #<User id: 1, name: "Bob", created_at: "2013-10-09 15:17:21", updated_at: "2013-10-09 15:17:21">
>> u.build_address
=> #<Address id: nil, user_id: 1, country: nil, created_at: nil, updated_at: nil>
>> u.valid?
=> false
>> u.errors
=> #<ActiveModel::Errors:0x007fe1d6919b18 #base=#<User id: 1, name: "Bob", created_at: "2013-10-09 15:17:21", updated_at: "2013-10-09 15:17:21">, #messages={:address=>["is invalid"]}>
>> u.address.errors
=> #<ActiveModel::Errors:0x007fe1d69197a8 #base=#<Address id: nil, user_id: 1, country: nil, created_at: nil, updated_at: nil>, #messages={:country=>["can't be blank"]}>