Rails 4:有一个代理模型来组合多个模型 [英] Rails 4: having a proxy model to combine multiple models
问题描述
我正在尝试使用导轨 (4).我之前做过一些 Sinatra.
I am trying my hand on rails (4). I have done some Sinatra earlier.
我有一个注册表单,用户可以在其中填写他的组织名称、地址和他自己的姓名、密码等.我有两个表 - 用户和组织,这些表填充了注册数据.所以,我有两个活动记录模型 users
和 organizations
.我的控制器如下所示:
I have a signup form, in which user can fill out his organization name, address and his own name, password etc. I have two tables - Users and Organizations, those table get populated with Signup data. So, I have two active records model users
and organizations
. My controllers looks as follows:
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
模型(数据库表).我正在寻找这样的 Registration
模型(我应该称其为模型吗?)在那里我可以有类似的东西:
I do not have any Registration
model (table in db). What I am looking for such Registration
model (should I call it model?) where I can have something like:
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
类?
1) So where should I keep this Registration
class?
2) 对于这种情况,这是正确的方法吗?如果没有,那么最好的方法是什么?
2) Is this a correct approach for such situation? If not, then what is the best way to do it?
3) 拥有这样的类会影响运行任何单元测试吗?
3) Having such class will effect running any unit tests?
4) 我看到有文件,signup_helper.rb
在 SignupsController
中有什么用
4) I see there is file, signup_helper.rb
what is the use of that in SignupsController
推荐答案
你可以在你的模型中做 include ActiveModel::Model
,它会像一个普通的 Model 一样工作.您将能够进行验证、回调.除了持久化到数据库之外的任何事情.
You can do include ActiveModel::Model
in your model, and it will behave as a normal Model. You will be able to do validations, callbacks. Anything other than persisting to a database.
看看这个 了解更多信息.
这篇关于Rails 4:有一个代理模型来组合多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!