go - 使用模型数组中的选项渲染 SelectTag()

标签 go buffalo

我有一个 User型号和 App我的应用程序中的模型。 App有一个 belongs_toUser 的关系模型。
在模板apps/new.plush.html我需要将用户列表呈现为下拉选择。我已经实现了forms.Selectable User中的如下界面模型 -

func (a *User) SelectLabel() string {
    return a.Name
}

func (a *User) SelectValue() interface{} {
    return a.ID
}
New() apps.go 中的操作看起来像这样 -
func (v AppsResource) New(c buffalo.Context) error {
    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return fmt.Errorf("no transaction found")
    }

    users := &models.Users{}
    if atErr := tx.All(users); atErr != nil {
        return c.Error(http.StatusNotFound, atErr)
    }

    c.Set("users", users)
    c.Set("app", &models.App{})

    return c.Render(http.StatusOK, r.HTML("/apps/new.plush.html"))
}

现在,我如何编写选择标签来呈现 users 中的选项大批?
以下不起作用 -
<%= f.SelectTag("UserID", {options: users})%>

最佳答案

我从#buffalo slack channel 找到了解决方案。问题在于 -

func (a *User) SelectLabel() string {
    return a.Name
}

func (a *User) SelectValue() interface{} {
    return a.ID
}
这些不应该是指针方法。正确的版本是——
func (a User) SelectLabel() string {
    return a.Name
}

func (a User) SelectValue() interface{} {
    return a.ID
}

关于go - 使用模型数组中的选项渲染 SelectTag(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62895236/

相关文章:

go - 使用 map[string]int 作为 map[interface{}]interface{} 类型的参数

go - 在测试Buffalo应用程序期间禁用信息日志

go - 在从 Golang Buffalo 网络应用程序发送推文时设置 CSRF token 时遇到问题

css - go buffalo 工作流程中生成的/public/assets 在哪里?

go - 无法在 gobuffalo 中验证和创建模型

go - 使用 go 从我的 sqlite 数据库中获取最后一条记录

import - Go 导入中的名称冲突

go - Go 上是否存在类似于 C++ 中的宏之类的东西,比如 #ifdef 这样我就可以根据标志选择要构建的内容?

windows - 如何使用 Go 在 Windows 上获取文件所有者?

go - 如何遍历请求参数