您好我有这两个类
class Company {
String company_name
static constraints = {
company_name size: 3..20, unique: true, nullable: false
}
String toString() { return company_name}
}
class Job {
String job_name
Company company
static constraints = {
job_name size: 3..20, unique: false, nullable: false
company nullable: false
}
String toString() { return job_name}
}
和这个方法:
def register(String company_name,String job_name)
{
def job = new Job(company : new Company(company_name : company_name), job_name: job_name)
if (job.validate() && job.save())
{
redirect(url:"https//localhost:8080")
}
}
我可以创建对象,例如Company:nvidia
,Job:worker
但如果我尝试为公司创建另一个职位nvidia- Company:nvidia
,Job:owner
我会收到错误原因?这是在if子句中
答案 0 :(得分:0)
您在unique
属性上有一个company_name
约束,而您的代码正在尝试为每个新的Company
实例创建一个新的Job
实例。
你应该这样做:
def nvidiaCompany = new Company(company_name: 'nVidia').save()
def jobDesigner = new Job(company: nvidiaCompany, job_name: 'designer')
def jobDeveloper = new Job(company: nvidiaCompany, job_name: 'developer')
所以你重用Company
实例。如果您只在代码中创建一个Job
实例,则必须先获取Company
实例:
def nvidiaCompany = Company.findByCompanyName('nvidia')
def jobDesigner = new Job(company: nvidiaCompany, job_name: 'designer')