使用Rails配置分类3

时间:2012-12-27 13:52:02

标签: ruby ruby-on-rails-3 categorization

我希望能够为我的用户分配类别(最多2个,允许1个)。我希望此用户的任何帖子只能从同一类别列表中分配一个类别(我的应用程序称为专业)。

目前,我已经配置了它,以便我可以为每个分配1,在用户,帖子和专业模型之间使用简单的belongs_to和has_many关联。这适用于帖子,因为它只需要1个职业分配,但对于用户来说它限制了2的能力。

用户的视图有两个下拉列表,由专业中的项目填充。我可以选择两种不同的职业,但只有一种保留专业的价值,我希望它保留两者或只接受一种,如果只选择一种。我的主要限制是在用户数据库中,只有一个专业列引用了profession_id。我无法复制专业列,那么如何设置它以便添加第二个专业字段?

或者,我应该如何更改数据库设计和模型以实现此目的?

user.rb:

    class User < ActiveRecord::Base
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

      attr_accessible :email, 
                      :password, 
                      :password_confirmation,
                      :remember_me, 
                      :first_name, 
                      :last_name, 
                      :profile_name, 
                      :full_bio, 
                      :mini_bio,
                      :current_password,
                      :photo,
                      :profession_id

      attr_accessor :current_password

      validates :first_name, :last_name, :profile_name, presence: true

      validates :profile_name, uniqueness: true,
                               format: {
                                  with: /^[a-zA-Z0-9_-]+$/
                               }

      has_many :posts
      belongs_to :profession

      has_attached_file :photo,
                        :default_url => 'default.png'


      def full_name
        first_name + " " + last_name
      end
    end

post.rb:

    class Post < ActiveRecord::Base
      attr_accessible :content, :name, :user_id, :profession_id
      belongs_to :user
      belongs_to :profession

      validates :content, presence: true,
                  length: { minimum: 2 }

      validates :name, presence: true,
                  length: { minimum: 2 }

      validates :user_id, presence: true

    end

profession.rb:

    class Profession < ActiveRecord::Base
      attr_accessible :name

      has_many :posts
      has_many :users
    end

1 个答案:

答案 0 :(得分:0)

在这种情况下,您的用户和专业的has_many :through关联可能效果最佳。使用“专业”之类的附加模型,您可以按如下方式对此关系进行建模:

class User < ActiveRecord::Base
  has_many :specialties
  has_many :professions, :through => :specialties
end

class Profession < ActiveRecord::Base
  has_many :specialties
  has_many :users, :through => :specialties
end

class Specialty < ActiveRecord::Base
  belongs_to :user
  belongs_to :profession
end

然后,您可以使用视图中的nested_form gem接受与该用户相关的专业。