Project

General

Profile

new habtm association between core User and plugin Category

Added by Miguel Akira about 12 years ago

I'm trying to save a new HABTM relationship between User and Category.

My User model:

class User < ActiveRecord::Base
    has_and_belongs_to_many :categories
end

My Category model:

class Category < ActiveRecord::Base
     has_and_belongs_to_many :users
end

I have the join table set up correctly. THe problem is, I cannot change anything on the User controller, only on the User view. So, in the User view, there's a collection_select:

<%= f.collection_select :category_ids, Category.all, :id, :title, 
    { :selected => @user.category_ids }, 
    { :multiple => true, :name => 'user[category_ids][]' } 
-%>


I can correclty choose the categories that my User belong to, but when I click submit, every other attribute is saved except the category, which is not updated on the join table.

If I inspect the params, I can see that the category_ids is being passed correctly:

"user"=>{"category_ids"=>["2", "4"]

But i can't do anything with it on the User controller, since I'm not allowed to mess with the code. Is there someway to automatically update the join table, or I have to manually update it?

Thanks!


Replies (2)

RE: new habtm association between core User and plugin Category - Added by Miguel Akira about 12 years ago

In order to do that, I had to extend the core Update method on my UsersController. To do that, I had to edit the init.rb of my plugin:

### init.rb

## regular init.rb stuff.......

require_dependency 'users_controller'

module UsersControllerPatch
  def self.included(base) # :nodoc:
    base.class_eval do
      unloadable # Send unloadable so it will not be unloaded in development

      def update_with_update_patch
           temp = update_without_update_patch
            @user.categories = Category.find(params[:user][:category_ids]) 
            return @user
      end
      alias_method_chain :update, :update_patch
    end
  end
end

UsersController.send(:include, UsersControllerPatch)

And that's it.

RE: new habtm association between core User and plugin Category - Added by ria sophieanty almost 8 years ago

maybe its too late for asking now
can you tell me how you set up the join table for the category and the user model? any/what changes you make at user model?
thanks

    (1-2/2)