0

我正在使用 simple_form 并且我有一个包含 3 个值的选择菜单,这些值会打印到索引中。我想知道获取用户设置的值的正确和最佳方法,然后计算当前有 3 种不同选择中的多少。

我是 ruby​​ 新手,所以这是一个很大的学习曲线,我们将不胜感激。

在我的 _form.html.erb

<%= f.input :menu, :as => :select, :collection => [ "Chocolate", "Cake", "Custard"] %>

我的 Index.html.erb

<td><%= reply.menu %></td>

D b

class CreateReplies < ActiveRecord::Migration
  def change
    create_table :replies do |t|
      t.string :name
      t.integer :menu
      t.boolean :rsvp, :default => false

      t.timestamps
    end
  end
end
4

1 回答 1

1
  1. 您正在寻求建立多对一的关系(对一个菜单的许多回复)
  2. 将您的迁移更改为 t.integer :menu_id
  3. 创建另一个名为 Menu 的模型,带有 id 和 ie 名称。

因此,请使用以下内容:

#  == 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 -"%>

然后其他所有内容大部分都为您自动化(即,当您创建/更新回复时,它将获取发布的 menu_id 并相应地分配它。

如果我是你,我会深入研究http://ruby.railstutorial.org/。这是一个极好的资源。

更新:忘记了您的视图显示(如果您尝试显示您选择的菜单的名称 - 如果您尝试显示整个菜单,那是完全不同的场景):

<td><%= @reply.menu.name %></td>
于 2012-11-23T00:56:28.190 回答