Edit an object using the HABTM association to modify the database before validation using ActiveAdmin

I had a problem trying to update a model with an association has_and_belongs_to_many.

Let's say that Post has_and_belongs_to_many Tag, a Postchecks for the presence of the header and Tags. If I update Postby deleting its title and tags, I get a validation error in titleand Tags, ok. But ActiveAdminalready deleted entries that establish a connection between Postand Tag, therefore, if I leave the edit page Post, it Postremains invalid in the database without Tags.

Here are my models:

class Tag < ActiveRecord::Base
  attr_accessible :label
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  attr_accessible :content, :title, :tag_ids
  has_and_belongs_to_many :tags
  validates_presence_of :content, :title, :tags
end

ActiveAdmin.register Post do

  form do |f|
    f.inputs do
        f.input :title
        f.input :content
        f.input :image
        f.input :tags
    end

    f.buttons
  end
end

I use chosen-rails gem and it allows the user to deselect all message tags.

, : ActiveAdmin .

- ?

Edit:

, :

Started PUT "/admin/posts/8" for 127.0.0.1 at 2013-04-01 10:32:07 -0300
Processing by Admin::PostsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"amSbLlP/rgDrNn/N8lgq/KEaRXK1fMPShZDwpZ0QIJ4=", "post"=>{"title"=>"", "content"=>"content", "tag_ids"=>["", ""]}, "commit"=>"Update Post", "id"=>"8"}
  AdminUser Load (0.2ms)  SELECT `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 1 LIMIT 1
  Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 8 LIMIT 1
  Tag Load (0.2ms)  SELECT `tags`.* FROM `tags` INNER JOIN `posts_tags` ON `tags`.`id` = `posts_tags`.`tag_id` WHERE `posts_tags`.`post_id` = 8
   (0.1ms)  BEGIN
  SQL (12.3ms)  DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = 8 AND `posts_tags`.`tag_id` IN (1, 2)
   (49.6ms)  COMMIT
   (0.1ms)  BEGIN
   (0.2ms)  ROLLBACK
  Post Load (0.3ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 8 LIMIT 1
  Tag Load (0.2ms)  SELECT `tags`.* FROM `tags` 
  Rendered /home/rodrigo/.rvm/gems/ruby-1.9.3-p125@blog/gems/activeadmin-0.5.1/app/views/active_admin/resource/edit.html.arb (192.3ms)
Completed 200 OK in 276ms (Views: 194.8ms | ActiveRecord: 63.3ms)

2:

, , ActiveAdmin .

ActiveRecord, , , . . :

1.9.3p125 :064 > post = Post.find(8)
  Post Load (0.3ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 8 LIMIT 1
 => #<Post id: 8, title: "title", content: "content", created_at: "2013-03-27 13:13:20", updated_at: "2013-03-27 13:13:20", image: "extrato.bmp"> 
1.9.3p125 :065 > post.tags
  Tag Load (0.2ms)  SELECT `tags`.* FROM `tags` INNER JOIN `posts_tags` ON `tags`.`id` = `posts_tags`.`tag_id` WHERE `posts_tags`.`post_id` = 8
 => [#<Tag id: 1, label: "tag", created_at: "2013-02-25 18:32:45", updated_at: "2013-02-25 18:32:45">, #<Tag id: 2, label: "new", created_at: "2013-02-25 18:32:50", updated_at: "2013-02-25 18:32:50">] 
1.9.3p125 :066 > post.title = ""
 => "" 
1.9.3p125 :067 > post.save #<<<<<<< It invalid on title
 => false 
1.9.3p125 :068 > post.tags = []  #<<<<<<< This shouldnt trigger database update
   (0.3ms)  BEGIN
  SQL (0.5ms)  DELETE FROM `posts_tags` WHERE `posts_tags`.`post_id` = 8 AND `posts_tags`.`tag_id` IN (1, 2)
   (55.5ms)  COMMIT
 => [] 
1.9.3p125 :069 > post.save #<<<<<<<  It invalid on title AND TAGS
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
 => false 
1.9.3p125 :070 > post.reload
  Post Load (0.2ms)  SELECT `posts`.* FROM `posts` WHERE `posts`.`id` = 8 LIMIT 1
 => #<Post id: 8, title: "title", content: "content", created_at: "2013-03-27 13:13:20", updated_at: "2013-03-27 13:13:20", image: "extrato.bmp"> 
1.9.3p125 :071 > post.valid? #<<<<<<< Now, I have this model in invalid state 
  Tag Load (0.6ms)  SELECT `tags`.* FROM `tags` INNER JOIN `posts_tags` ON `tags`.`id` = `posts_tags`.`tag_id` WHERE `posts_tags`.`post_id` = 8
 => false 

( ) ?

+5
4

@Rodrigo , HABTM, [] [1]

[1]: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many :

=

Replaces the collection’s content by deleting and adding objects as appropriate.

, ,

:

Override ActiveRecord < < has_many: ,

, .

+1

tmp . , .

:

models/article.rb:

class Article < ActiveRecord::Base
  validate :author_presence
  has_and_belongs_to_many :authors

  attr_writer :tmp_author_ids

  def tmp_author_ids
    @tmp_author_ids || author_ids
  end

  def author_presence
    if tmp_author_ids.reject(&:blank?).empty?
      errors.add(:tmp_author_ids, 'Author is missing')
    else
      self.author_ids = tmp_author_ids
    end
  end
end

admin/article.rb, form:

f.input :tmp_author_ids, as: :select, multiple: true, collection: Author.all, label: 'Authors'

0

, active_admin, , -

ActiveAdmin.register Post do

  controller do
    def update
      if params[:post][:tag_ids] == ["", ""]
        flash.now[:alert] = "You can't remove all tags"
        render :edit
      else
        super
      end
    end
  end
...
end

,

attr_accessor :new_tag_ids

validate :validate_new_tags_ids

after_save :update_tags

def update_tags
    self.tag_ids = @new_tag_ids if defined?(@new_tag_ids)
    @new_tag_ids = nil
end

private 
def validate_new_tags_ids
    errors[:tags] << "can't be blank (2)" if @new_tag_ids.blank? 
end
-1

All Articles