activeadmin habtm better example for uniqueness case - ruby-on-rails-3

Am able to manage habtm as per follow, and I wanted a better way for this
I have habtm between User and Tag on Rails 3, aa 0.5.1
Tag name is uniq
f.input :tags, :label => 'Assign existing tag'
# this above allows to select from existing tags, but cannot allow to create one
f.has_many :tags, :label => 'Add new tags, modify existings' do |ff|
ff.input :name
ff.input :_destroy, :as => :boolean
end
# this above allows to create new one but not allow to specify existing one
# if we specify existing one, uniqueness wont let create this one, neither existing get used
# and throws validation error
any hints?
Adding my models
class User < ActiveRecord::Base
has_and_belongs_to_many :tags
scope :tagged_with, lambda {|tags| joins(:tags).where("tags.name" => tags)}
accepts_nested_attributes_for :tags, :allow_destroy => true
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :users
validates :name, :uniqueness => { :case_sensitive => false }
end

Try this,
f.label => 'Assign existing tag'
f.select :tags, Tag.all.map{|t| [t.tag_name, t.id]}, {:prompt => "Select Tag name" }
this above allows to select from existing tags, don't have option to create one
For the Second thing add this line in the model,
validates :tags, :uniqueness => {:scope => :tag_name}
here the :tag_name is your name of the fieldname. This throw an error if the tag name already exists when you create a duplicate.
It's just an idea as per your question. This won't be your exact answer because your specification is not enough to give you the exact answer.

Related

How to check emptiness on devise custom fields?

I've added two news fields to my users table :first_name and :last_name
In migration file I've specified these fields couldn't be null using the following code:
class Userscustomfields < ActiveRecord::Migration
def change
add_column :users, :first_name, :string, {:null => false, :limit => "128"}
add_column :users, :last_name, :string, {:null => false, :limit => "128"}
end
end
I've checked on my database and the table was configurated correctly. But when I'm going to do a new register, my rails app allows to me to add a new user with first and last names empty. The app saves the fields with "", which didn't worked as I expected.
How can I do prevent this, by making a check of emptiness on my field before save them on my database?
I put on model user.rb
validates :first_name, :last_name, presence: true

rails activerecord validation with associations

I have model associations as follows:
class Group < ActiveRecord::Base
has_many :group_links, :dependent => :destroy
end
class GroupLink < ActiveRecord::Base
belongs_to :group
validates_presence_of :group_id
validates_presence_of :url, :message => "We need a url to create a link"
validates_uniqueness_of :url, :message => "A link with this url already exists"
validates_presence_of :text, :message => "We need a text to create a link"
validates_uniqueness_of :text, :message => "A link with this text already exists"
end
I want it to work like in each group the group links should be unique. However the way it works is, it throws the validations errors even if some other group has thins group link.
what am i doing wrong?
thanks in advance,
I used :scope => :group_id for my uniqueness validations to get this to work

cant setup an active admin resource form with has many :through assoc

I'm working on a rails (3.7.8) app and using active admin to manage resources for the ff models:
class AdminUser < ActiveRecord::Base
has_many :user_article_categories, :include => :article_categories
has_many :article_categories, :through => :user_article_categories,
:source => :admin_user
has_many :articles, :through => :user_article_categories,
:source => :admin_user
# ...
end
class UserArticleCategory < ActiveRecord::Base
belongs_to :admin_user
belongs_to :article_category
attr_accessible :admin_user_id, :article_category_id, :included
attr_accessor :included
after_find :set_included
private
def set_included
self.included = "1"
end
# ...
end
the "included" attribute was based on a solution presented here
class ArticleCategory < ActiveRecord::Base
has_many :user_article_categories, :include => :admin_users
has_many :admin_users, :through => :user_article_categories,
:source => :article_category
has_many :articles, :through => :user_article_categories,
:source => :article_category
# ...
end
but I seem not to get setting up (correctly) a form for admin_users, such that creating a new admin_user would have all article_categories displayed as a list of checkboxes
while a persisted admin_user for update would have all article_categories checkboxes displayed but wit all previously set article-categories checked, so that an update would remove unchecked checkboxes and add newly checked ones to what goes to the join-table
for admin/admin_users.rb I create the form as follows, this does not work, though it renders correctly, any help will be appreciated
form do |f|
if f.object.persisted? and current_admin_user.id == f.object.id
f.inputs "Admin Details" do
f.input :email
f.inputs :for => user_article_categories do |usr_art_catr|
usr_art_catr.input :article_category_id, :hidden
usr_art_catr.input :included
end
end
else
f.inputs "Admin Details" do
f.input :email
f.input :superuser, :label => "Super User Priveleges"
f.input :article_categories, :as => :check_boxes,
:collection => ArticleCategory.select("id, name")
end
end
f.buttons
end
Actually, to display a list of checkboxes of all article_categories and check all already checked article categories for a given admin_user on update.
Formtastic, when rendering the show form for the form's object, calls a method provided on the form object via
f.input :method_to_be_called, :as => :checkboxes
which formtastic would compare its result with a collection provided via
the
:collection => any_valid_ruby_object
but both should return the same kinds; array/array or hash/hash, whatever, to determine which checkboxes should be checked, by performing a difference on the two collections.
The method called by formtastic could be an instance method on admin_user that queries the join-table, to determine which checkboxes should be checked and builds an array of that from the related article_categories table or returns an empty array when there is none.
This allows formtastic do what is right, as least in this context. This solution makes the "included" attribute on user_article_categories (the join-table) redundant!

Rails: validation fail for a nested model on key field presence check

I have a model User and a nested model Mobility
class User < ActiveRecord::Base
has_many :mobilities, :dependent => :destroy
accepts_nested_attributes_for :mobilities
end
and
class Mobility < ActiveRecord::Base
belongs_to :mobile_user, :class_name => 'User'
validates :city_id, :presence =>true
validates :user_id, :presence =>true
validates :city_id, :uniqueness => {:scope => [:user_id]}
end
my view
=form_for #user, :as => :user, :html =>{ :class => 'form-horizontal'} do |f|
=f.fields_for :mobilities do |city_form|
=city_form.text_field :city_id, :id => "city_id_#{index}"
= f.submit "Retour"
my problem is that when I submit the form Rails render me this validation error:
Mobilities user > doit ĂȘtre rempli(e)
But if a I comment this line:
#validates :user_id, :presence =>true
Both, my Mobility and User objects get saved and know what: user_id field of #mobility is OK (indicatie my #user's ID)
If I send the form with 2 identical mobility inside, both model get saved but it seems my validation of uniqueness didn't check nothing because i have 2 Mobility object with same user_id and city_id in my database...
In fact it seems like my validation can't read my user_id 's key when validating.
I understand that because my User model did'nt get saved yet and doesnt have any ID yet... but that is my question:
How can i check both: presence of user_id and uniqueness with scope ???

has_many association with conditions on ActiveRecord

I have this models: Store and Address.
The second model Address I'm using this with other models and has some custom fields inside for different models.
Yes like polymorphic but without the varchar field for Class, I'm using an integer. (optimization stuff)
now on my Store model the association in set like this:
class Store < ActiveRecord::Base
has_many :addresses, :foreign_key => "parent_id", :conditions => ['parent_kind = ?', 2]
accepts_nested_attributes_for :addresses
end
Now in my controller I do:
#store.addresses.build
And I can use f.fields_for :addresses... inside the form.
The problem comes out when I submit the form and the data is saved to the database.
The record in the stores table is saved, the record in addresses is saved with the parent_id of the store in place, but the parent_kind is in 0 which is the default value for that attribute on MySQL.
My Quick fix was this:
#store = Store.new(params[:store])
#store.addresses[0].parent_kind = 2
if #store.save
....
But I know there must be another way.
Anny suggestions?
Thanks.
Did you try using a hidden field in your nested form?
<%= f.fields_for :addresses, Address.new do |ff| %>
<%= ff.hidden_field :parent_kind, :value => 2 %>
...
EDIT
If you don't want to use it due to security concerns, here's another way that might help. You can try using an association callback like so:
class Store < ActiveRecord::Base
has_many :addresses, :foreign_key => "parent_id",
:conditions => ['parent_kind = ?', 2],
:before_add => Proc.new { |store,address| address.parent_kind = 2}
accepts_nested_attributes_for :addresses
end