簡體   English   中英

在form_for,rails中傳遞collection_selection和text_field值

[英]Passing a collection_selection and text_field values in a form_for, rails

吸引力模型屬於目的地。

我正在嘗試創建一個新的吸引力(text_field:name),但也將其鏈接到一個已經創建的目的地。 這些目的地在帶有該collection_select標記的下拉菜單中呈現。 通過單擊提交,我希望使用“目標”外鍵將景點創建並保存在activerecord數據庫中。

f.collection_select(:attraction,:destination_id,Destination.all,:id,:name)%>

目前,整個塊如下所示:

<h1>New attraction</h1>

選擇一個城市

<%= f.collection_select(:attraction, :destination_id, Destination.all, :id, :name) %>   

<div class ="field">
  <%= f.label :name %>
  <%= f.text_field :name %>
</div>

<div class="actions">
  <%= f.submit %>
</div>

如何使用適當的目的地將景點保存到數據庫中? 提前致謝!!

我沒有使用f.collection_select()所以不確定在params內部調用什么,但是對於以下代碼,假設它是params[:attraction][:destination_id] 您可以將創建操作更改為:

def create
  @destination = Destination.find(params[:attraction][:destination_id])
  @attraction = @destination.attractions.build(params[:attraction])
  if @attraction.save
    ...
  else
    ...
  end
end

假設您已經創建了has_manybelongs_to關聯。

如果遇到質量分配錯誤,則將第一行更改為:

@destination = Destination.find(params[:attraction].delete(:destination_id))
# this will return the deleted value, and in the next line of code
# you'll have the rest of the params still available

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM