2012-08-07 63 views
0

我已經改名爲SessionsController和會話模型週期/週期,因爲它與衝突設計,所以你會看到這樣的更新填充Rails的形式隨着模型的信息從另一個控制器

我有一個會議和事件模型/控制器。當創建新會話時,它需要與特定事件關聯。

在我的會話模型中,我有一個event_id,但我希望在填充名稱爲非過去事件的表單上有一個下拉列表。一旦選擇了該選項,表單應該能夠將正確的event_id分配給創建的會話。

要做到這一點,正確的方法是什麼?

這是我schema.rb來幫助你的模型是什麼樣子更清晰的畫面:

ActiveRecord::Schema.define(:version => 20120807154707) do 

    create_table "events", :force => true do |t| 
    t.string "name" 
    t.date  "date" 
    t.string "street" 
    t.string "city" 
    t.string "state" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

    create_table "sessions", :force => true do |t| 
    t.string "name" 
    t.integer "event_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

    create_table "users", :force => true do |t| 
    t.string "email",    :default => "", :null => false 
    t.string "encrypted_password", :default => "", :null => false 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",  :default => 0 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.datetime "created_at",        :null => false 
    t.datetime "updated_at",        :null => false 
    t.boolean "admin",    :default => false 
    end 

    add_index "users", ["email"], :name => "index_users_on_email", :unique => true 

end 

這裏是我的形式:

<%= form_for(@period) do |f| %> 


    <%= f.label :Name %> 
    <%= f.text_field :name%> 

    <%= f.label :Event %> 
    <%= f.collection_select(:period, :event_id, Event.all, :id, :name)%> 


    <%= f.label :time %> 
    <%= f.text_field :time, id: "timepicker" %> 

    <%= f.submit "Create Event" %> 

<% end %> 

,我不斷收到以下錯誤:undefined method合併'爲:名稱:符號'

分解收集選擇的各種參數:f.collection_select(:period, :event_id, Event.all, :id, :name)

:period -> The object 
:event_id -> the method I want to set on the object. 
Event.All -> The collection (for now I'll take all of them) 
:id -> the value of the html element option 
:name -> the value displayed to the user 

我這樣做是否正確?

+0

見下文。總之,您需要使用collection_select而不使用「f」對象,它可以工作。 – 2012-08-08 14:51:26

回答

1

要顯示帶有來自其他型號(不是另一個控制器)的選件的選擇菜單,請嘗試collection_select

在新的會議形式,這可能是這樣的:

collection_select(:event, :id, Event.where("date > :date", date: Time.now.strftime("%m/%d/%Y")) 

在會話控制器,在create行動,建立這樣的關係:

@session.event = Event.find(params[:event][:id]) 
+0

這讓我指出了正確的方向。我知道我需要使用collection_select,但我現在還沒有工作。查看更新以獲取更多信息。 – 2012-08-08 14:42:26

+0

仍然沒有通過過濾日期過濾工作的形式,但通過刪除f.collection_select,我能夠得到它的工作。 – 2012-08-08 14:50:48

0

我發現,這結構適用於我:

<%= f.label :event %> 
     <%= f.collection_select :event_id, Event.all, :id, :name, {:prompt=> "Pick an Event"}, {:class => "form-control"} %> 

最後一位是html部分w我曾經設置Bootstrap類。

:name這裏可能是:date:street等等

相關問題