我有一个用户表和一个组织表。注册用户时,应用程序还会为您创建新组织。我通过将此代码放在user.rb中来完成此操作:
class User < ActiveRecord::Base
before_create :create_organization
belongs_to :organization
private
def create_organization
self.organization = Organization.create :name => self.name
end
end
但是在某些情况下,参数将通过URL传递,例如
http://localhost:3000/sign_up?organization_id=10
如何创建某种if-then语句,以便在存在organization_id
参数时,用户模型不会创建新组织..而是提交现有的organization_id
参数作为用户的organization_id?
答案 0 :(得分:4)
简单地将检查添加到您的模型中,
def create_organization
organization = Organization.create :name => name unless organization_id.present?
end
在您的控制器中,只需从organization_id
设置params
。
答案 1 :(得分:0)
self.organization = Organization.find(organization_id) rescue Organization.create :name => name
,即使未设置find
,ActiveRecord::RecordNotFound
也会引发params[:organization_id]
。