gpt4 book ai didi

ruby-on-rails - F.select 输入在编辑时不保存值

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:02 25 4
gpt4 key购买 nike

我的 Rails 应用程序中有一个来自此辅助方法的 f.select 输入。

def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method)
collection.map do |group|
option_tags = options_from_collection_for_select(
group.send(group_method), option_key_method, option_value_method)

content_tag(:optgroup, option_tags, :label => group.send(group_label_method))
end.join.html_safe
end

View 中的select如下所示。

<%= f.select(:type_id, option_groups_from_collection_for_select(@categories, :types, :category, :id, :name)) %>

当保存帖子时,正确的 type_id 被保存,但是当我去编辑帖子时,select 并没有像预期的那样显示当前选择的项目。我假设我的代码有问题。

这是我的类别模型

has_many :posts
has_many :types, :order => "name"

这是我的类型模型

belongs_to :category

最佳答案

您必须提供第 5 个参数,即选定的键。试试下面的代码:

<%= f.select(:type_id, option_groups_from_collection_for_select(@categories, :types, :category, :id, :name, f.object.type_id)) %>

f.object.type_id 返回表单中传递的对象的 type_id 属性(如果有的话)。否则,它将为 nil,并且不会选择任何内容。

关于ruby-on-rails - F.select 输入在编辑时不保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20526466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com