我正在尝试使用它的关系创建简单的表单来保存帖子。 这是我的域名模型;
发布模型;
class Post {
String title
String teaser
String content
static belongsTo = [author: Person, category: Category]
static hasMany = [tags: Tag]
static constraints = {
}
}
标签模型;
class Tag {
String name
static belongsTo = Post
static hasMany = [posts: Post]
static constraints = {
}
}
我已经创建了一个用于通过html格式保存帖子对象的表单;
<g:form controller="posts" action="save" method="post">
<div class="input">
<label for="post.title">Title:</label>
<g:textField name="post.title" />
</div>
<div class="input">
<label for="post.teaser">Teaser:</label>
<g:textField name="post.teaser" />
</div>
<div class="input">
<label for="post.content">Content:</label>
<g:textArea name="post.content" />
</div>
<div class="input">
<label for="post.content">Category:</label>
<g:select optionKey="id" optionValue="name" name="post.category" from="${categories}" noSelection="['':'-Choose Category-']"/>
</div>
<div class="input">
<label for="post.tags">Tags:</label>
<g:select optionKey="id" optionValue="name" name="post.tags" from="${tags}" noSelection="['':'-Choose Tags-']" />
</div>
<div class="input">
<g:submitButton name="Create" value="Create" />
</div>
</g:form>
这是控制器逻辑;
def save() {
def post = new Post(params.post)
post.author = springSecurityService.currentUser
if(post.save()){
flash.message = "Post created successfully..."
redirect(action: "index", method: "GET")
}
else{
flash.error = "Something went wrong, please check the form again!"
[tags: Tag.list(), categories: Category.list()]
render(view: "create")
}
}
通过这种方式,我无法保存帖子对象的标签。