0

私は simple_form を使用しており、インデックスに出力される 3 つの値を持つ選択メニューがあります。ユーザーが設定した値を取得するための正しくて最良の方法を知りたいです。次に、3 つの異なる選択肢のうち現在いくつあるかを数えます。

私はルビーを初めて使用するので、これは大きな学習曲線であり、助けていただければ幸いです。

私の _form.html.erb で

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

私のIndex.html.erb

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

デシベル

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. 多対 1 の関係 (1 つのメニューに多数の返信) を作成しようとしている
  2. 移行を t.integer :menu_id に変更します
  3. id と ie name を使用して、Menu という別のモデルを作成します。

したがって、次のようなものでロールします。

#  == 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 に答える