我正在尝试在play-authenticate模块的User模型和我的模型之间创建一个关系 - Books。我正在使用play 2.0.4并且我已将play-authenticate集成到我的项目中。在我的控制器/应用程序中,我有getLocalUser方法:
public static User getLocalUser(final Session session) {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session));
return localUser;
}
我正在我的图书模型中尝试覆盖模型的方法来保存添加/修改图书记录的用户。
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
我这样做的错误,我不明白是:
方法session()未定义为Books类型。
由于我的导入,我不确定这是怎么回事,因为我可以访问控制器/应用程序方法:
import controllers.Application;
更新: *
public static Result createBook() {
Form<Book> filledForm = bookForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(
views.html.bookCreator.render(Book.all(), filledForm)
);
}
else {
Book.create(filledForm.get());
//Book.save(getLocalUser(session()));
return redirect(routes.Application.createSuccess());
}
}*
答案 0 :(得分:2)
首先在模型类中调用session()
是一个非常糟糕的主意,因为如果你这样做,你将创建某种循环依赖(表示层 - &gt;模型 - &gt;表示层)
如果你真的想保持这种方式,那就这样做:
控制器:
public static User getLocalUser() {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session()));
return localUser;
}
型号:
public void save() {
User logged = Application.getLocalUser();
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser();
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
但我更愿意这样做:
控制器:
public Result anAction() {
...
save(getLocalUser(session()));
...
}
型号:
public void save(final User logged) {
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o, final User logged) {
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}