2012-09-09 2 views
0

나는이 관계가있는 경우, has_and_belongs_to_many의 HABTM 필드

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :topics 
end 

class Topics < ActiveRecord::Base 
    has_and_belongs_to_many :articles 
end 

가 이미 주제 아래 테이블에 저장 주제의 미리 정의 된 목록을 가지고있다. 각 기사에는 주제가과 3 개 있어야합니다. 내가 을 작성하면 코드는 컨트롤러보기에서 어떻게 보이나요? 가장 효율적이고 정확한 방법은 무엇입니까?

답변

2

양식에 세 개의 스피너 필드를 추가하고 주제 ids를 데이터 및 주제 이름으로 레이블로 채 웁니다. 다행히도 대부분의 무거운 짐을 덜기위한 형태의 헬퍼가 있습니다. collection_select에 대한 자세한 내용은 See here을 참조하십시오. 다음은 해당 링크에서 가져온 예제입니다.

<%= collection_select(:person, :city_id, City.all, :id, :name) %> 

컨트롤러에서 선택한 ID를 기반으로 필요한 연결을 만들 수 있습니다. 그것은 다음과 비슷한 모습이 될 것입니다

_form.html.erb

<% form_for @article do |f| %> 
    ... 
    <%= collection_select(:article, :topic_id_1, Topic.all, :id, :name) %> 
    <%= collection_select(:article, :topic_id_2, Topic.all, :id, :name) %> 
    <%= collection_select(:article, :topic_id_3, Topic.all, :id, :name) %> 
    ... 
<% end %> 

acticle_controller.rb

def create 
    ... 
    @article.topics << Topic.find params[:topic_id_1] 
    @article.topics << Topic.find params[:topic_id_2] 
    @article.topics << Topic.find params[:topic_id_3] 
    ... 
end