I have a collection select in my form:
<div class="field">
<%= f.label :area %>
<%= f.collection_select(:area_id, Area.all, :id, :name, include_blank: "No area.") %>
And my model validation has no requirement for an area.
It was my understanding that by using include_blank would allow me to choose nil. However i get a validation error "Area must exist"
EDIT:
Here is the important code in the model:
has_many :ratings, dependent: :destroy
has_many :noise_ratings, dependent: :destroy
has_many :statuses, dependent: :destroy
has_many :checkins, dependent: :destroy
has_and_belongs_to_many :features
belongs_to :area
belongs_to :campus
validates :name, presence: true, uniqueness: { scope: :campus_id, message: "unique space for each campus." }
validates :description, presence: true
validates :campus_id, presence: true
Rails 5 forces you to set all belongs_to associations unless you specify optional: true. It was added to prevent data inconsistencies, so, in case you want it to behave like previous rails versions, you just have to change your association to this:
belongs_to :area, optional: true
In Rails 5 validate is set to true by default. Please check for :optional and :required options on belongs_to documentation for more details.
Related
I have associations as follows:
variant has_may colours and colours has_many sizes. I am using active admin gem for managing backend activities. My models looks like,
class Variant < ApplicationRecord
has_many :variant_colours, dependent: :destroy
accepts_nested_attributes_for : variant_colours, allow_destroy: true
end
class VariantColor < ApplicationRecord
belongs_to :variant
has_many :variant_sizes, dependent: :destroy
accepts_nested_attributes_for :variant_sizes, allow_destroy: true
end
class VariantSize < ApplicationRecord
belongs_to :variant_color
end
It is building variant_colours form with given fields but it is not building variant_sizes form under variant colours. Building meaning it does not populate fields on the form(UI)
form do |f|
f.inputs do
f.input :name
f.input :product
f.input :sku
f.input :stock_quantity
f.inputs do
f.has_many :variant_colors, heading: 'Variant Colors',
allow_destroy: true,
new_record: true do |color_form|
color_form.input :color
color_form.input :sku_code
color_form.input :stock
color_form.inputs do
color_form.has_many :variant_sizes, heading: 'Variant Sizes',
allow_destroy: true,
new_record: true do |size_form|
size_form.input :size
size_form.input :sku_code
size_form.input :stock
end
end
end
end
end
f.actions
end
May not need to wrap f.has_many with anything, so you could try removing one or both of the nested f.inputs and color_form.inputs that you have wrapping your has_many input blocks in the form.
My next thought would be, how are you declaring the permitted params in your controller? They probably need to be something along the lines of:
permit_params :name, :product, :sku, :stock_quantity,
variant_colors_attributes: [
:color, :sku_code, :stock, :_destroy,
# I don't think I've ever tried to double nest in this way, you may need diff syntax
variant_sizes_attributes: [:size, :sku_code, :stock, :_destroy]
]
My guess is the issue is in your permitted params.
i'm new to ActiveAdmin and Rails and i struggle on something to build up my ActiveAdmin interface.
Consider the following models :
class PageType < ActiveRecord::Base
has_many :fields, class_name: 'PageField'
accepts_nested_attributes_for :fields, allow_destroy: true
end
class PageField < ActiveRecord::Base
belongs_to :page_type
has_many :page_has_fields
has_many :pages, through: :page_has_fields
accepts_nested_attributes_for :page_has_fields, allow_destroy: true
end
class PageHasField < ActiveRecord::Base
belongs_to :page
belongs_to :page_field
end
class Page < ActiveRecord::Base
belongs_to :page_type
has_many :page_has_fields, dependent: :delete_all
has_many :page_fields, through: :page_has_fields
accepts_nested_attributes_for :page_fields, allow_destroy: true
end
In Active Admin I want to create some page templates to handle "static" pages. And in each of the pages, I want to update the content of each fields related to the templates page.
Thus far, what I did worked with this code :
ActiveAdmin.register Page do
permit_params :name, :page_type_id, :page_id,
:page_fields_attributes => [:id, :name, :field_type, :page_id,
:page_has_fields_attributes => [:id, :content, :page_id]
]
form do |f|
f.inputs
f.has_many :page_fields, heading: false, new_record: false do |g|
g.inputs :name, :required
g.has_many :page_has_fields, new_record: false do |h|
h.input :content if h.object.page_id == f.object.id
end
end
f.actions
end
end
But the second has_many seems really wrong to me, and i'm sure there are a better solution to this problem.
If i don't go with the "if", inputs are created for the right fields, but for every single page.
Is there a way to specify an ID or a parameter in has_many ? Or a better tag to handle situation like this ?
Thanks
Try changing your setup to something more like this
ActiveAdmin.register Page do
...
form do |f|
f.inputs do
f.input :some_column
f.input :some_other_column
f.input :page_fields, as: :check_boxes, checked: PageField.all.map(&:name)
f.input :page_has_fields, as: :check_boxes, checked: PageField.all.map(&:content)
end
f.actions
end
end
Decided to update the information here based upon the feedback I have received to date and what I currently have setup.
I have been trying to work out the best way to solve this issue but so far I am not coming up with an answer. I have two tables: customers and credit_cards. A customer can have many credit_cards and a credit_card belongs to a customer. Also, a customer can have many addresses and an addresses belongs to a customer.
In my creditcard table I have a column that indicates if a particular credit card is primary. The column name is primary. A customer can have many creditcards but only ONE can be primary.
I was hoping that this could be done via validations but so far I am coming up empty. I've done numerous searches but nothing seems to work :(
The following post seems to indicate how this can be done but I couldn't get this to work:
Validation Solution?
My customer.rb model file is as follows. It's not the entire code in there but the relevant parts.
class Customer < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_many :creditcards, :dependent => :destroy
accepts_nested_attributes_for :creditcards, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_one :primary_creditcard, ->{ where(primary: "1") }, class_name: Creditcard, autosave: true
validates :addresses, presence: true
validates :creditcards, presence: true
validates :primary_creditcard, presence: true
end
My creditcard.rb model file is as follows.
class Creditcard < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
belongs_to :customer
validates :name, presence: true, length: { maximum: 30}
validates :card_type, presence: true
validates :card_number, presence: true
validates :card_exp, presence: true
validates :card_code, presence: true
end
When I create a new customer with an address and a credit card I always get an validation error message that states the following:
Primary creditcard can't be blank
I would appreciate any help on this.
As per the request, adding in the code from the controller that saves the data:
if #customer.update_attributes(customer_params)
flash[:success] = 'Member was successfully updated.'
else
flash[:error] = "Member was not updated, please see errors."
end
The above is in the update part of the customer controller.
Also, for reference, the customer_params is defined as follows:
def customer_params
params.require(:customer).permit(:first_name, :last_name, :sex, :dob, :cell_phone, :work_phone, :home_phone, :other_phone, :email1, :email2, :referred_via_id,
:referred_cust_id, :cust_notes,
addresses_attributes: [:id, :customer_id, :name, :line1, :line2, :line3, :city, :county, :state, :zip, :billing, :delivery, :addr_notes],
creditcards_attributes: [:id, :customer_id, :name, :card_type, :card_number, :card_exp, :card_code, :primary])
end
You could add an additional relation called primary_creditcard and validate it's presence
class Customer < ActiveRecord::Base
has_many :credit_cards
has_one :primary_creditcard, ->{ where(primary: true) }, class_name: CreditCard
validates :primary_creditcard, presence: true
end
I'm having trouble validating a model from a has_many through association. Below are the relevant models:
Broadcast Model
class Broadcast < ActiveRecord::Base
attr_accessible :content,
:expires,
:user_ids,
:user_id
has_many :users, through: :broadcast_receipts
has_many :broadcast_receipts, dependent: :destroy
validates :user_id, presence: true
validates :content, presence: true
end
Broadcast Receipt Model
class BroadcastReceipt < ActiveRecord::Base
belongs_to :broadcast
belongs_to :user
attr_accessible :user_id, :cleared, :broadcast_id
validates :user_id , presence: true
validates :broadcast_id , presence: true
end
There is also an association with Users that have_many broadcasts receipts through broadcast receipts.
The problem appears to be with the following line:
validates :broadcast_id , presence: true
Whenever I try to create a Broadcast, I get a rollback with no error messages given. However, when removing the above line, everything works as expected.
This looks like a problem with the Broadcast not being saved before the Broadcast Receipts are being created.
Is there any way I'd be able to validate the broadcast_id is set on the receipt model?
This appears to be the same issue discussed here: https://github.com/rails/rails/issues/8828, which was solved by adding :inverse of to the has_many associations to the join model.
There might be some problem in your code structuring. You could give this version a try.
class Broadcast < ActiveRecord::Base
# I assume these are the recipients
has_many :broadcast_receipts, dependent: :destroy
has_many :users, through: :broadcast_receipts
# I assume this is the creator
validates :user_id, :content, presence: true
attr_accessible :content, :expires, :user_id, :user_ids
end
class BroadcastReceipt < ActiveRecord::Base
belongs_to :broadcast
belongs_to :user
# You should be able to validate the presence
# of an associated model directly
validates :user, :broadcast, presence: true
attr_accessible :cleared
end
I've got a text_field for tags in a nested form(It's being associated with Trips) that is being split on a comma on save and saving the words in the string seperated by the comma. I've jumped through some hoops to make it happen, and it's happening as I want by now. The only downside is that it seems that it doesn't make the current tag a unique tag(If it exists associate the existing one with the new Trip instead of making a new tag)
Here's the code splitting and saving the tag seperately:
if params[:trip][:tags_attributes].present?
params[:trip][:tags_attributes].each do |tag|
#a = tag[1]['title']
#a.split(',').each do |single|
#trip.tags.find_or_initialize_by_title(single)
end
end
end
And just in case my Trip.rb:
class Trip < ActiveRecord::Base
attr_accessible :description, :title, :user_id,
:triplocations_attributes, :photo, :category_ids,
:start_city, :tripphotos_attributes, :img_url, :thumb_url, :images,
:tags_attributes, :province
# validates :title, :length => {:minimum => 3}
# validates :description, :presence => true
# validates_associated :tags
has_many :triplocations, :dependent => :destroy
has_many :tripphotos, :dependent => :destroy
has_and_belongs_to_many :categories
has_and_belongs_to_many :tags
accepts_nested_attributes_for :triplocations, allow_destroy: true
accepts_nested_attributes_for :tripphotos, allow_destroy: true
accepts_nested_attributes_for :categories
accepts_nested_attributes_for :tags
end
Thanks in advance!