美好的一天。我是grails和groovy的新手,我想做的是将一个域对象(在我的情况下为相册对象)添加到另一个域(购物车)中。当用户在查看相册时单击“添加到购物车”链接时,HomeController的“购买”操作应创建该相册的副本并将其放入购物车域,除非我不知道该怎么做。这就是我得到的。
class HomeController{
def index(){
//displays a list of albums and a 'add to cart' link at each album in the list
}
def buy(){
//Here's where the code should go.
redirect(controller: "home", action: "index")
}
}
最佳答案
我认为在尝试使用 View / Controller 之前,您需要对domainClasses进行更多考虑:
您有一个域对象(在我的情况下是相册对象)到另一个域(购物车)
域类:
class User {
String name
static hasMany = [orders:Orders]
}
Class Album {
String name
}
class Order {
User user
Album album
}
View : Controller 操作以显示以下内容:
<!-- by defining user.id and album.id when grails receives the .id it binds that id to the actual object so --!>
<!-- User user = params.user // is the user object bound to user.id --!>
<g:form action="save" controller="myController">
<g:hidden name="user.id" value="1"/>
<g:select name="album.id" from="${mypackage.Album.list()}" optionKey="id" optionValue="name"/>
<g:submitButton name="save">
</g:form>
接收该保存操作的 Controller -保存功能应真正移交给事务服务=这只是为了向您展示非常基本的内容:
package mypackage
class MyController {
def save() {
Order order= new Order(params)
order.save()
//
//User user=User.get(params.user.id)
User user=params.user
user.addToOrders(order)
user.save()
render "album added to order class and then order added to users class"
}
}
关于grails - 没有将域对象添加到另一个域而没有域之间的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35934595/