첫째, 생각 - 대부분의 시간, 제품은 여러 종류가 있지만, 각각의 카테고리는 많은 제품이 포함되어 있습니다. 어쩌면 당신의 협회는 다 대다가되어야할까요? 귀하의 실제 질문에.
정확하게 알았다면 질문은 실제로 데이터베이스에서 서로 관련된 카테고리 및 제품을 만드는 방법입니다. 즉, 새 카테고리를 만들 때 product_id
값을 설정하는 방법입니다.
명확성을 위해 필요할 경우 product_id는 카테고리으로 설정됩니다. 결국 카테고리는 해당 제품에 속하므로 소유자 ID가 있어야합니다.
자, 기존 제품에 속하는 새로운 카테고리를 구축하려는 가정 해 봅시다 - 당신이 할 수 있습니다 :
이
# in your view, where you link from products/show.html.erb to category/new.html.erb
<%= link_to "Build new category for this product", new_category_url(:id => @product.id) %>
# you must have @product defined, and you also must have
# 'resources :categories' in your routes file
# in your controller action categories/new, set the new category's product id:
def new
@category = Category.new(:product_id => params[:id])
end
# include a hidden field to contain the product_id in your new form
<%= form_for @category do |f| %>
<%= f.hidden_field :product_id %>
... other fields, labels, etc.
<% end %>
# save the record as you normally would (analogous to the code in your comment to @Chowlett).
@category = Category.new(params[:category])
if @category.save
redirect_to :action => "list", :notice => "Category saved successfully."
else
render :action => "new"
end
위의 코드는 당신이 제품, 각 범주를 구축 할 수 있도록 하나의 별 -하나. 따라서 제품을 먼저 제작 한 다음 제품/쇼 페이지에서 카테고리/새 양식으로 연결되는 링크를 포함하여 해당 카테고리가 속한 제품의 ID를 전달합니다.
제품을 빌드하고 카테고리를 동시에 만들고 싶다면, 좀 더 복잡합니다. 이에 대한 자세한 내용은 http://railscasts.com/episodes/196-nested-model-form-part-1 (3 부작 중 첫 번째 시리즈) 및 https://github.com/ryanb/nested_form을 참조하십시오. 위의 기본 사항에 매우 만족하지 않는 한이 행동 방침을 제안하지 않습니다. 레일스를 처음 접했을 때 나는이 코드에 일주일이 지났습니다!
고맙습니다. 많은 도움이되었습니다. – user659068
당신을 진심으로 환영합니다! :) – sscirrus
대단한 답변입니다! 나는 두 부분으로 된 질문을 가지고 있는데, 이것은 첫 부분을 완벽하게 대답했다. 만약 당신이 분, 내 질문의 두 번째 부분에서 균열을 가지고 신경 쓰시겠습니까 [여기] (http://stackoverflow.com/questions/5813528/how-to-pass-foreign-key-attributes-down- through-a-nested-form-in-rails-3)? 중첩 된 형태로만이 질문과 관련이 있습니다. – FattRyan