【问题标题】:How to make a many to many association in rails如何在 Rails 中建立多对多关联
【发布时间】:2014-12-30 05:10:46
【问题描述】:

我正在尝试使用 Rails 4 制作论坛应用程序。我希望用户拥有许多论坛,因此我知道我需要多对多关系。我有一个表格来保存新论坛的标题和描述。到目前为止,我有 3 个表,用户、论坛和 forums_users。当我创建一个新表单并将其添加到论坛数据库时,一切都很好。我的问题是如何获取信息以访问 forums_users 表?因为现在当我提交表单时,它不会将信息添加到关联表中。 这是我的论坛迁移文件。

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

提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 associations


    【解决方案1】:

    如果您想从连接表forum_users 中获取数据,请使用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
    

    现在您可以使用UserForum 模型访问/获取forum_users 表数据

    【讨论】:

      【解决方案2】:

      使用对当前用户的引用创建论坛,例如:

      @forum = current_user.forums.create(forum_params)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        相关资源
        最近更新 更多