views:

48

answers:

2

I am having trouble with some theory.

I have a model called Promos, and I also have a model called Categories.

I want the admin to be able to create set Categories from which the users will select in a dropdown to assign the Promo. So Promos will belong to a Category but the assignment ought to happen in the create.

What is the recommended structure?

A: 

A user has_many a promos, which belongs to a category. A category has_many promos.

Such as:

class User < Activerecord::Base
    has_many :promos

class Promo < Activerecord::Base
    belongs_to :user
    belongs_to :category

class Category < Activerecord::Base
    has_many :promos
CodeJoust
< is the subclass operator, not >. You would need to associate Category to User or add `attr_accessor :user` to Category allowing the controller to pass a user to a Category. Which can be used in the before create test. Which, as you wrote it has too many issues to correct from a comment.
EmFi
A: 

To ensure that every Promo has a Category:

class Category < ActiveRecord::Base
  has_many :promos
end

class Promo < ActiveRecord::Base
  belongs_to :category

  validates_association_of :category
end

How to set the Category at Promo creation time

promo = Promo.new(:category => @category)

As far as forms go:

<% form_for :promo do |f| %>
  <%= f.collection_select :category_id, Category.all, :id, :name, :prompt => "Choose a category" %>
  ...
    Other promo fields
  ...
<% end %>

Matching controller code:

class PromosController < ActionController
  def create
    @promo = Promo.create(params[:promo])
    ...
      redirect or render whether @promo was successfully created
    ...
  end
end
EmFi
Getting error on the promo newuninitialized constant for categories on this line:<%= f.collection_select :category_id, Categories.all, :id, :name, :prompt => "Choose a category" %> I defined categories like this in create: @categories = Category.find(:all)
Kevin Compton
You're absolutely right. It should be Category.all, not Categories.all. It sounds right when you think it, but the model name is always singular.
EmFi