Rails 4:拥有一个代理模型来组合多个模型
我正在尝试我的手(4)。 我早些时候做了一些Sinatra。
我有一个注册表单,用户可以在其中填写他的组织名称,地址和他自己的名字,密码等。我有两个表 – 用户和组织,这些表填充了注册数据。 所以,我有两个活跃的记录模型users
和organizations
。 我的控制器如下所示:
class SignupsController < ApplicationController # GET /signup def new # show html form end # POST /signup def create @signup = Registration.register(signup_params) respond_to do |format| if @signup.save format.html { redirect_to @signup, notice: 'Signup was successfully created.' } else format.html { render action: 'new' } end end end private # Never trust parameters from the scary internet, only allow the white list through. def signup_params params[:signup] end end
我没有任何Registration
模型(db中的表)。 我正在寻找这样的Registration
模型(我应该称之为模型吗?),我可以在这里找到类似的东西:
class Registration def self.register params o = Organization.new params u = User.new o.id, params self.send_welcome_email params[:email] end def send_welcome_email email #send email here end end
1)那么我应该在哪里Registration
这个Registration
课程?
2)对于这种情况,这是正确的方法吗? 如果没有,那么最好的方法是什么?
3)有这样的课程会影响任何unit testing吗?
4)我看到有文件, signup_helper.rb
在SignupsController
有什么SignupsController
您可以在include ActiveModel::Model
中include ActiveModel::Model
,它将表现为普通模型。 您将能够进行validation,回调。 除了持久存储到数据库之外的任何东西。
有关详细信息,请查看此内容。
class Registration include ActiveModel::Model def self.register params o = Organization.new params u = User.new o.id, params self.send_welcome_email params[:email] end def send_welcome_email email #send email here end end
回答你的问题:
1)我会将注册类移动到app / models中的注册模块(因为它与注册用例有关):
# apps/models/signup/registration.rb module Signup class Registration ... end end
2)我喜欢你的方法。 这是我会做的事情。 它不是“Rails方式”,但在我看来它更优越。
3)没有。拥有PORO(普通旧ruby物体)目前适用于任何unit testing,您可以轻松测试它。
4)帮助者(在我看来)是在视图(和控制器)之间共享function的旧的和过时的方式。 不要使用它们,除非绝对没有其他办法(也许某些图书馆要求它……)。 像你一样使用PORO总是更好。
除非您需要ActiveModel :: Model,否则不必包含ActiveModel :: Model。 例如validation。 在这种情况下,您可以包含其function的各个部分。 例如
include ActiveModel::Validations