category structure
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 Cat开发者_开发知识库egories 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?
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
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
精彩评论