Question

I have this code:

class ArticlesController < ApplicationController
  active_scaffold :articles do |config|
   config.label = "Manage my articles"
   config.actions.exclude :show

    form_cols = [:name, :summary, :content, :author, :category, :article_date]

      config.columns = form_cols

      config.list.sorting = {:content_file_name => :asc}
      config.columns[:category].css_class = 'categories'
      config.columns[:category].clear_link
      config.columns[:category].form_ui = :select
......

and models

class Article < ActiveRecord::Base
  belongs_to :category, :class_name => 'Category'
end

class Category < ActiveRecord::Base
  has_many :articles, :foreign_key => :category_id
end

Category is mapped on this table

CREATE TABLE `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `active` tinyint(1) DEFAULT '1',
  `group` varchar(255) DEFAULT 'novel',
  PRIMARY KEY (`id`)
);

i want to show only categories with a particular "group" depending on the user_type. The problem is that i don't know how to filter the rows in a relation. I can see that activescaffold perform two queries, one for the articles and a second for the Category ( SELECT * FROM categories) so a want to change this second query (like SELECT * FROM categories where group='something'. do you have any suggestion?

thanks

Was it helpful?

Solution

If I understand the question, you need to filter the categories available in select menu for new and edit article, basing on a parameter. If this is the case, you can override options_for_association_conditions(association) in articles_helper, for example:

module ArticlesHelper
  def options_for_association_conditions(association)
    if association.name == :category
      ['categories.id IN (?)', current_user.available_groups.map(&:id)]
    else
      super
    end
  end
end

see: https://github.com/activescaffold/active_scaffold/wiki/Custom-Association-Options

Another option could be customize how the select is rendered adding a _category_form_column partial in views/articles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top