我正在通过RubyOnRails开发一个门户网站,学生,老师和家长可以参加不同的艺术作品竞赛。
有3个实体:Contests
,Categories
(竞争对手类别/年龄组)和Nominations
(各种活动)。 Contest
可以有多个Categories
。每个ContestCategory
都可以有多个Nominations
。每个Category
都可以属于多个Contests
。每个Nomination
都可以属于许多ContestCategories
。所以我假设Contests
和Categories
之间存在多对多关系,ContestCategories
和Nominations
之间存在多对多关系。我创建了以下模型:Contest
(contest.rb),Category
(category.rb),Nomination
(nomination.rb),ContestCategory
(contest_category。 rb)和ContestCategoryNomination
(contest_category_nomination.rb)。
我的模特:
class Category < ActiveRecord::Base
has_many :contest_categories
has_many :contests, through: :contest_categories
end
class Contest < ActiveRecord::Base
has_many :contest_categories
has_many :categories, through: :contest_categories
has_many :nominations, through: :contest_categories
has_one :provision
end
class ContestCategory < ActiveRecord::Base
belongs_to :contest
belongs_to :category
has_many :contest_category_nominations
has_many :nominations, through: :contest_category_nominations
end
class ContestCategoryNomination < ActiveRecord::Base
belongs_to :contest_category
belongs_to :nomination
end
class Nomination < ActiveRecord::Base
has_many :contest_category_nominations
has_many :contest_categories, through: :contest_category_nominations
has_many :contests, through: :contest_categories
end
我想在创建新Contest
期间创建基于ajax的模态窗口,以将其与Category
关联,并选择属于此Nominations
的多个Category
。
ContestsCategoriesController
或
ContestCategoryNominationsController
或可能是
ContestCategoryNominationsController
?new_category
采取行动吗?
CategoriesController
中的new
或ContestsCategoriesController
行动
或new
中的ContestsCategoriesNominationsController
行动?答案 0 :(得分:0)
这完全取决于你想如何操纵你的对象。如果您只想通过竞赛修改所有属性和关系,您只需要ContestsController。使用像accept_nested_attributes_for
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html这样漂亮的小方法,您可以提供所有相关值,甚至是相关记录。
答案 1 :(得分:0)
参考你在评论中提到的要求,我将在模态对话框中创建一个表单,它代表一个表单对象,如:
class Nomination::Category
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
# validates :your_attributes
def initialize(category, attributes = {})
@category = category
@attributes = attributes
end
def persisted?
false
end
def save
return false unless valid?
if create_objects
# after saving logic
else
false
end
end
# more business logic according to your requirements
private
def create_objects
ActiveRecord::Base.transaction do
# @category.contests = ... saving logic
@category.save!
end
rescue
false
end
end
和代表控制器:
class NominationCategoriesController < ApplicationController
def new
category = Category.find params[:category_id]
@nomination_category = Nomination::Category.new category
end
def create
category = Category.find params[:category_id]
@nomination_category = Nomination::Category.new category, params[:nomination_category]
@nomination_category.save
end
end
请注意,这只是一个例子/想法。具体实现取决于您的特定业务逻辑要求。