0

ユーザーにカテゴリを割り当てられるようにしたい(最大2つ、1つを許可)。このユーザーによる投稿には、同じカテゴリのリスト(私のアプリでは職業と呼ばれます)から1つのカテゴリのみを割り当てたいと思います。

現在、ユーザー、投稿、および職業モデル間に単純なbelongs_toおよびhas_manyの関連付けを使用して、それぞれに1を割り当てることができるように構成しています。これは、1つの職業の割り当てしか必要としないため、投稿には問題なく機能しますが、ユーザーには2つの能力が制限されます。

ユーザーのビューには、職業のアイテムが入力された2つのドロップダウンリストがあります。2つの異なる職業を選択できますが、職業の価値を保持するのは1つだけです。両方を保持するか、1つだけが選択されている場合は1つだけを受け入れます。私の主な制限は、ユーザーデータベースには、profession_idを参照するprofession列が1つしかないことです。職業列を複製できないので、2番目の職業フィールドを追加できるように設定するにはどうすればよいですか?

または、これを実現するためにデータベースの設計とモデルをどのように変更する必要がありますか?

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
4

1 に答える 1

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を使用して、そのユーザーに関連付けられた職業を受け入れることができます。

于 2012-12-27T22:42:28.177 に答える