与Gorm一起庆祝“未定义:页面”。

huangapple go评论87阅读模式
英文:

Revel with Gorm "undefined: Page"

问题

我只会为你提供翻译服务,以下是你要翻译的内容:

我只是想用revelgormpq创建一个新项目。
我在app/models中有一个Page模型:

package models

import (
	"time"
)

type Page struct {
	Id        int64
	Title     string `sql:"size:255"`
	Context   string
	Url       string
	MetaKeys  string
	MetaDescr string
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt time.Time
}

以及在app/controllers中的gorm.go

package controllers

import (
	_ "myapp/app/models"
	_ "code.google.com/p/go.crypto/bcrypt"
	_ "database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
	_ "github.com/revel/revel"
	"github.com/revel/revel/modules/db/app"
)

var (
	DB gorm.DB
)

func InitDB() {
	db.Init()

	var err error
	DB, err = gorm.Open("postgres", "user=postgres dbname=mydb_development sslmode=disable")
	if err != nil {
		panic(fmt.Sprintf("Got error when connect database, the error is '%v'", err))
	}

	DB.LogMode(true)

	DB.AutoMigrate(Page{})
}

我在DB.AutoMigrate(Page{})这一行中遇到了undefined: Page的错误,但是我在_ "myapp/app/models"这一行中已经引入了我的模型。出了什么问题?

英文:

I'm just trying to create new project with revel, gorm and pq.
I have model Page in app/models:

package models

import (
	"time"
)

type Page struct {
	Id        int64
	Title     string `sql:"size:255"`
	Context   string
	Url       string
	MetaKeys  string
	MetaDescr string
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt time.Time
}

and gorm.go in app/controllers:

package controllers

import (
	_ "myapp/app/models"
	_ "code.google.com/p/go.crypto/bcrypt"
	_ "database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
	_ "github.com/revel/revel"
	"github.com/revel/revel/modules/db/app"
)

var (
	DB gorm.DB
)

func InitDB() {
	db.Init()

	var err error
	DB, err = gorm.Open("postgres", "user=postgres dbname=mydb_development sslmode=disable")
	if err != nil {
		panic(fmt.Sprintf("Got error when connect database, the error is '%v'", err))
	}

	DB.LogMode(true)

	DB.AutoMigrate(Page{})
}

I have the error undefined: Page in line DB.AutoMigrate(Page{}), but I linked my models in line _ "myapp/app/models". What's wrong?

答案1

得分: 2

你忘记添加你的模型的包标识符了:由于你的模型结构定义在另一个包中,它的名称(在controllers包内部)应该是models.Page

如果你真的想要去掉包标识符,并像本地定义一样操作,我认为你也可以通过将models包分配给.标识符来在本地导入它。示例:

import (
    . "myapp/app/models"
)
英文:

You forgot to add the package identifier of your model: as your model struct is defined in another package, it's name (locally to the controllers package) should be models.Page.

If you really want to get rid of the package identifier and do like it was locally defined, I think that you can also import your models package locally by assigning it to the . identifier. Example:

import (
    . "myapp/app/models"
)

huangapple
  • 本文由 发表于 2014年6月25日 21:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/24409631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定