I'm newbie to groovy. How can we call domain methods from controller in Grails.
Controller :
def results = User.fetch_results
User Domain :
def fetch_results {
def users = this.get(1)
}
Sorry if the above code is wrong, i need to know how to access domain methods from controller.
thanks.
My code is like this
Us开发者_StackOverflow中文版erController:
def results = User.addUser
User domain:
def addUser {
def user = new User()
user.id = 1
user.publication_name = pub_name
user.publication_desc = ""
user.edit_date = new Date()
user.save()
}
}
I tried with above code but getting errors . how can we call "addUser" method from controller ?
thanks.
You need to make the method a static method.
class User {
def static addUser() {
def user = new User()
...
user.save()
}
}
Then make sure to import the User object in your controller.
I think a
User usr = User.get(1) // or User.findBy... etc
in your controller should do what you want. Just check out the GORM documentation from the Grails Docs, they are really good. If you are new to Groovy but not Java you should check the Groovy Documentation before to get a feeling for the Groovy language itself.
Assuming you want a list of all users and your domain class is defined as User
def userList=User.list()
Assuming you want to access a specific field on user number 2
def theAddress=User.get(1).address
Note this assumes you've imported what ever package your domain classes are defined in.
精彩评论