【问题标题】:Grails: How to define a domain property rendered on views but not persisted?Grails:如何定义在视图上呈现但不持久的域属性?
【发布时间】:2013-07-23 05:31:56
【问题描述】:

我有这个域类,比方说:

class Person {
  String name
  Integer age
  //car data that needs to be shown and filled in views 
  //but not persisted in Person class
  String model
  String color

  static afterInsert = {
    def car = new Car(model: model, color: color)
    car.save()
  }
}

class Car {
  String model
  String color  
}

我需要在我的Person 视图(createedit)中显示在Person 类中定义的模型和颜色属性,但这些不必与此类保持一致。这些数据modelcolor 必须使用Car 域类可能使用afterInsert 事件进行持久化。换句话说,我需要使用来自另一个域类的视图来保存来自域类的数据。

提前致谢。

【问题讨论】:

    标签: grails gsp grails-domain-class


    【解决方案1】:

    您可以在您希望 GORM 忽略的属性上使用 transients,例如

    class Person {
    
      static transients = ['model', 'color']
    
      String name
      Integer age
      //car data that needs to be shown and filled in views 
      //but not persisted in Person class
      String model
      String color
      ..
    }
    

    只是好奇,但有没有你不使用关联的原因

    class Person {
      ..
      static hasMany = [cars: Car]
    }
    
    class Car {
      ..
      static belongsTo = [Person] 
      static hasMany = [drivers: Person]
    }
    

    .. 或作曲

    class Person {
      Car car
    }
    

    或简单地与多个域进行数据绑定

    //params passed to controller
    /personCarController/save?person.name=John&age=30&car.model=honda&car.color=red
    
    //in your controller
    def person = new Person(params.person)
    def car = new Car(params.car)
    

    【讨论】:

    • 感谢您的回答。我已经尝试过了,但是视图中没有呈现模型和颜色字段。
    • 只是好奇 - 你有什么理由不使用关联、组合或只是 data binding with multiple domains
    • 是的,我认为有一个可以定义的关系,但对于我的问题,它不是很有必要。最好检查一辆车是否存在并检索它的数据,可能使用它的 ID,如果它不存在,则通过弹出窗口创建一辆新车。
    • 如果您只想在多个域上进行数据绑定,我在最后提供了一个示例
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2021-11-19
    • 2015-02-19
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多