2014-12-30 18 views
0

레일 4로 포럼 응용 프로그램을 만들려고합니다. 사용자가 많은 포럼을 갖고 싶기 때문에 다 대 다 관계가 필요합니다. 새로운 포럼의 제목과 설명을 저장하는 양식이 있습니다. 나는 지금까지 3 개의 테이블, 사용자, 포럼 및 forums_users 있습니다. 모든 것은 새로운 양식을 만들 때 훌륭하게 작동하며 포럼 데이터베이스에 추가됩니다. 제 질문은 forums_users 테이블로 이동하는 정보를 얻는 방법입니다. 현재 양식을 제출할 때 협회 테이블에 정보를 추가하지 않기 때문에. 다음은 포럼 용 마이 그 레이션 파일입니다.레일에서 many to many 연관을 만드는 방법

def up 
    create_table :forums do |t| 
    t.string :title 
    t.text :description 
    t.string :logo 
    t.boolean :is_active, default: true 
    t.timestamps 
    end 
    add_index :forums, :title 
    create_table :forums_users, id: false do |t| 
    t.belongs_to :forum, index: true 
    t.belongs_to :user, index: true 
    end 
end 
def down 
    drop_table :forums 
    drop_table :forums_users 
end 

이들은 나의 모델입니다.

class Forum < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :forums 
end 

다음은 포럼 컨트롤러

def create 
    @forum = Forum.new(forum_params) 
    @forum.save 
    respond_to do |format| 
    format.html{redirect_to admin_path, notice: 'New forum was successfully created.'} 
    end 
end 
private 
def forum_params 
    params.require(:forum).permit(:title, :description, :logo, :is_active) 
end 

내 만드는 방법입니다 그리고 여기 당신이 제출 한 형태입니다.

= simple_form_for(:forum, url: {action: :create, controller: :forums}) do |f| 
    = f.error_notification 
    .form-inputs 
    = f.input :title, autofocus: true 
    = f.input :description, as: :text 
    .form-actions 
    = f.button :submit 

감사합니다.

답변

1

UserForum을 사용하여 forum_users 테이블 데이터에 액세스/가져 오기

0

예를 들어 현재 사용자에 대한 참조를 사용하여 포럼을 만들기 : 당신이 다음 지금 has_many :through

class Forum < ActiveRecord::Base 
    has_many :users, through: :forum_users 
    end 

    class User < ActiveRecord::Base 
    has_many :forums, through: :forum_user 
    end 


    class ForumUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :forum 
    end 

을 수행 할 수 있습니다 사용하여 테이블을 조인 forum_users에서 데이터를 얻고 싶다면

@forum = current_user.forums.create(forum_params) 
관련 문제