简体   繁体   English

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

[英]Render SelectTag() with options from an array of models

I have a User model and a App model in my application.我的应用程序中有一个User model 和一个App model。 App has a belongs_to relation with User model. AppUser model 具有belongs_to关系。

In the template apps/new.plush.html I need to render the list of users as a drop down selection.在模板apps/new.plush.html ,我需要将用户列表呈现为下拉选择。 I have implemented forms.Selectable interface like below in the User model -我已经在User model 中实现forms.Selectable接口,如下所示 -

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

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

The New() action in apps.go looks like this - apps.go中的New()操作如下所示 -

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"))
}

Now, how do I write the Select Tag to render the options from the users array?现在,如何编写 Select 标记来呈现users数组中的选项?

Below is not working -以下不起作用 -

<%= f.SelectTag("UserID", {options: users})%>

I have found the solution from #buffalo slack channel.我从#buffalo slack 频道找到了解决方案。 The issue is with -问题在于 -

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

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

These should not be pointer methods.这些不应该是指针方法。 The correct version is -正确的版本是——

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM