2017-08-01 30 views
1

我在我的應用中使用搜索gem Ransack進行搜索。在我的表格中,我似乎有所有的工作,但我只能得到表單來顯示a)id或b)對象本身。我似乎無法正確映射到數據的名稱,而不是它的ID。試圖將id映射到在Rails中使用表單的名稱

有什麼想法?

表單代碼:

<!-- office type --> 
<%= f.collection_select :office_type_id_gteq, Desk.all, :id, :office_type_id, include_blank: "Office type", class: "form-control" %> 

模型&模式:

class OfficeType < ActiveRecord::Base 
    has_many :desks 

end 

class Desk < ActiveRecord::Base 

    belongs_to :office_type 

end 

模式

create_table "desks", force: :cascade do |t| 
    t.string "listing_name" 
    t.integer "min_days" 
    t.integer "max_days" 
    t.text  "description" 
    t.string "location" 
    t.integer "accommodate" 
    t.integer "user_id" 
    t.datetime "created_at",       null: false 
    t.datetime "updated_at",       null: false 
    t.integer "daily_rate" 
    t.integer "office_type_id" 
    t.integer "desk_type_id" 
    t.string "amenity_ids", default: "--- []\n" 
    t.float "latitude" 
    t.float "longitude" 
    t.boolean "active" 
    end 


    create_table "office_types", force: :cascade do |t| 
    t.string "office_type" 
    t.integer "desk_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

所以當它代表我可以看到office_type_id看我收集在下拉在形式中。我可以將其更改爲office_type,但這會引入對象本身,而不是稱爲office_type的字符串值。

正試圖將office_type_id映射到office_type字符串,但似乎無法得到該工作。我知道Desk.all可以添加到控制器中的一個變量,它很容易我直接在窗體中看看是否可以開始工作。

再次感謝。

回答

1

https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

這告訴你如何使用collection_select。但首先我認爲你是錯誤地構建模型的。如果辦公室類型有多個辦公桌,則不能有辦公桌ID,因爲這會將其連接到一個辦公桌。你將需要刪除此列,由於工作的關係,通過第桌上的辦公類ID

如果我「米理解正確,那麼你想要的是:

<%= f.collection_select :office_type_id, OfficeType.all, :id, :office_type, include_blank: false, class: "form-control" %> 

這將創建一個下拉菜單屬性'office_type_id',將所有Office類型作爲選項,在選中時發送其ID,並使用他們的Office Type屬性決定在下拉列表中顯示的內容。

+0

嗨@Mark,非常感謝您爲清除。因爲我的模型已經用下劃線命名,我試圖調用Office_type.all並得到一個錯誤。不能相信我沒有注意到t他的。 在事物的關係結束嗯,他們總是混淆我。我想這裏發生的事情是,我是從關係開始,然後修改它們。現在不刪除ID列它確實有效,但我會仔細考慮事情的結尾。 再次感謝您的建議和快速響應。傳說! – Bradley

+0

易犯錯誤,樂於幫助:) – Mark

相關問題