伙计们,我有 3 张桌子,如下所示:
- 项目 {id, name, owner, ....}
- ProjectMilestones {id, project_id, name ....}
- UserProjects {id, project_id, ....}
在这里,一旦我创建了一个新项目,我将获取Project_ID (@@IDENTITY)列,并使用此 ID在ProjectMilestones和UserProjects表中创建一个新行。我的代码如下所示
def create
ActiveRecord::Base.transaction do
# Instantiate a new object using form parameters
@project = Project.new(params[:project])
if @project.save
# if project saves, Create a new insteance into User Projects
@userproject=UserProject.new(
:project_id=>@project.id
)
@userproject.save
# Create a new insteance into ProjectMilestone
@projectmilestone=ProjectMilestone.new(
:project_id=>@project.id,
:milestone_id=>12,
:milestone_date=>@project.created_at
)
@projectmilestone.save
flash[:notice] = "A new project has been created successfully"
redirect_to(:action => 'list')
else
# If save fails, redisplay the form so user can fix problems
render('new')
end
end
end
它对我来说很好。我想知道有没有可用的优化方法?所以我可以将业务逻辑移动到模型并让项目创建所有关联的记录或失败