Ruby on rails 从Ruby simple_表单菜单中获取select项的值并计算结果
我使用的是simple_表单,我有一个包含3个值的选择菜单,可以打印到索引中。我想知道获得用户设置的值的正确且最佳的方法,然后计算当前3种不同选择中的数量 我是ruby新手,所以这是一个巨大的学习曲线,任何帮助都将不胜感激 在my_form.html.erb中 My Index.html.erb 分贝 您正在寻找对一个菜单进行多对一关系的多个回复 将迁移更改为t.integer:menu\u id 创建另一个名为Menu的模型,带有和id,即名称。 因此,请执行以下操作:Ruby on rails 从Ruby simple_表单菜单中获取select项的值并计算结果,ruby-on-rails,ruby,Ruby On Rails,Ruby,我使用的是simple_表单,我有一个包含3个值的选择菜单,可以打印到索引中。我想知道获得用户设置的值的正确且最佳的方法,然后计算当前3种不同选择中的数量 我是ruby新手,所以这是一个巨大的学习曲线,任何帮助都将不胜感激 在my_form.html.erb中 My Index.html.erb 分贝 您正在寻找对一个菜单进行多对一关系的多个回复 将迁移更改为t.integer:menu\u id 创建另一个名为Menu的模型,带有和id,即名称。 因此,请执行以下操作: # == Schem
# == Schema Information
#
# Table name: replies
#
# id :integer not null, primary key
# menu_id :integer
# ...
# created_at :datetime not null
# updated_at :datetime not null
class Reply < ActiveRecord::Base
attr_accessible :menu_id, etc.
belongs_to :menu, :inverse_of => :replies # belongs_to because has the FK
...
end
# == Schema Information
#
# Table name: menus
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
class Menu < ActiveRecord::Base
attr_accessible :name
has_many :replies, :inverse_of => :menu, :dependent => :nullify # the FK is in the reply
accepts_nested_attributes_for :replies
end
由于您使用的是SimpleForm:
<%= f.association :menu, :collection => Menu.all, :prompt => "- Select -"%>
然后,大部分其他内容都是为您自动完成的,即当您创建/更新回复时,它将获取发布的菜单id并相应地分配它
如果我是你,我会深入研究。这是一个极好的资源
更新:如果您试图显示所选菜单的名称,则忘记视图显示-如果您试图显示整个菜单,则完全是另一种情况:
<td><%= @reply.menu.name %></td>
感谢您提供的详细解决方案,我今晚将尝试此方案,如果效果良好,我将接受。非常感谢!很抱歉回复太慢,仍在解决此问题。在您有表模式信息的地方,我假设我做了一次数据库迁移来调整我的数据库。我知道这可能是一个不着边际的问题,但我很清楚模式信息只是显示了该模型的数据库中的字段。实际模型中的注释符号是使用一个名为annotate的gem生成的。是的,您需要创建一个迁移来创建这些字段和db:migrate和db:test:prepare。我可以问一下为什么底部的表:菜单被注释掉了吗?很抱歉,为了方便起见,我刚刚在注释信息中插入了一些不准确的内容,这些内容主要是注释的内容,而不是注释的内容,同时尝试快速获得正确的格式,以详细说明基础表模式。看起来,这可能会让您感到困惑,而不仅仅是帮助,只需删除模式注释即可。同时,我将再次查看它,并确保模式信息都设置为注释,这当然不是迁移中的注释!。
# == Schema Information
#
# Table name: replies
#
# id :integer not null, primary key
# menu_id :integer
# ...
# created_at :datetime not null
# updated_at :datetime not null
class Reply < ActiveRecord::Base
attr_accessible :menu_id, etc.
belongs_to :menu, :inverse_of => :replies # belongs_to because has the FK
...
end
# == Schema Information
#
# Table name: menus
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
class Menu < ActiveRecord::Base
attr_accessible :name
has_many :replies, :inverse_of => :menu, :dependent => :nullify # the FK is in the reply
accepts_nested_attributes_for :replies
end
<%= f.association :menu, :collection => Menu.all, :prompt => "- Select -"%>
<td><%= @reply.menu.name %></td>