我在項目中有一個多重has_many關係,並且正在尋找如何使用表單更新值的幫助。相同模型的不同實例(通過關聯多個has_many)
有兩種基本模式:產品和國家。產品可以來自多個來源國家,並有多個目的地國家。 (我不能拿出一個很好的比喻爲例子)
create_table "nations", force: :cascade do |t|
t.string "name"
end
create_table "products", force: :cascade do |t|
t.string "name"
t.string "bio"
end
create_table "dest_nation", force: :cascade do |t|
t.integer "product_id"
t.integer "nation_id"
end
create_table "orig_nation", force: :cascade do |t|
t.integer "product_id"
t.integer "nation_id"
end
然後我創建的關係如下:
class Product < ActiveRecord::Base
has_many :dest_nations
has_many :destination, :class_name=> 'nations', through: :dest_nation
has_many :orig_nations
has_many :origin, :class_name=> 'nations', through: :orig_nations
end
class Nation < ActiveRecord::Base
has_many :dest_nations
has_many :imports, :class_name => 'products', through: :dest_nation
has_many :orig_nations
has_many :exports, :class_name =>'products', through: :orig_nations
end
class DestNation < ActiveRecord::Base
belongs_to :nation
belongs_to :product
end
class OrigNation < ActiveRecord::Base
belongs_to :nation
belongs_to :product
end
問題: 1)當產品被註冊,我想了解用戶可以從選項列表中選擇的源和目標國家。我如何在視圖和控制器中進行這些更改以適當反映這些更改。
<%= form_for @product do |f|%>
<div class="form-group">
<%= f.label :name, "Name of the product:"%>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :bio, "A brief summary:"%>
<%= f.text_area :bio, class: "form-control", rows:3%>
</div>
<!-- For origination country -->
<%= f.collection_check_boxes :nation_ids, Nation.all, :id, :name do |cb|%>
<% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text}%>
<% end %>
<br>
<!-- For destination country -->
<%= f.collection_check_boxes :nation_ids, Nation.all, :id, :name do |cb1|%>
<% cb1.label(class: "checkbox-inline input_checkbox") {cb1.check_box(class: "checkbox") + cb1.text}%>
<% end %>
<br>
<%= f.submit "Submit", class: "btn btn-default btn-primary" %>
<%end%>
我的產品控制器
def create
@product = Product.new(product_params)
if @product.save
flash[:success] = ""
redirect_to root_path
else
render 'new'
end
# binding pry
end
def product_params
params.require(:product).permit(:name,:bio, nation_ids: [])
end
你有沒有想過使用simple_form寶石更新? https://github.com/plataformatec/simple_form。它會爲你提供協會助手,然後你可以使用,例如:'f.association:destinations' – IngoAlbers