RoR - 给用户'一个或多个标准目标'使用[has_many]或[belongs_to]

时间:2016-02-16 08:21:36

标签: ruby-on-rails ruby model

这是我的用户模型:../ db / migrate /

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.timestamps null: false
    end
    add_index :users, :email, unique: true
  end
end

这是我的目标模型:../ db / migrate /

class CreateGoals < ActiveRecord::Migration
  def change
    create_table :goals do |t|
      t.string :choice
      t.timestamps null: false
    end
  end
end

我想要实现的目标是为用户提供一个或多个目标。这些不是唯一的目标,但是其他任何用户也可以使用ABCD或E等五个预定的东西。

我尝试在def change之上实现belongs_to和has_many,但无济于事 - 每个rake db:migrate都没有成功。

感谢您提供任何帮助,我们非常感谢。

2 个答案:

答案 0 :(得分:3)

class Goal
  belongs_to :user # define relation
end

class User
  has_many :goals  # define relation
end

class CreateGoals < ActiveRecord::Migration
  def change
    create_table :goals do |t|
      t.references :user, index: true, null: false # <====== add user_id to goal
      t.string :choice
      t.timestamps null: false
    end
  end
end

答案 1 :(得分:1)

  

这些不是唯一的目标,而是其他任何用户也可以拥有的五个预定的内容,例如ABCD或E。

这将完全适用于has_many :through

#app/models/user.rb
class User < ActiveRecord::Base
  has_many :user_goals
  has_many :goals, through: :user_goals
end

#app/models/user_goal.rb
class UserGoal < ActiveRecord::Base
  belongs_to :user
  belongs_to :goal

  validates :goal, uniqueness: { scope: :user } #-> only unique entries
end

#app/models/goal.rb
class Goal < ActiveRecord::Base
  has_many :user_goals
  has_many :users, through: :user_goals
end

这样,每个User都可以有任何一个预定的目标:

#config/routes.rb
resources :users #-> url.com/users/:user_id/edit

#app/controllers/users_controller.rb
class UsersController < ApplicationController
  def edit
    @user = User.find params[:id]
  end

  def update
    @user = User.find params[:id]
    @user.update user_params
  end

  private

  def user_params
    params.require(:user).permit(goal_ids: [])
  end
end

#app/views/users/edit.html.erb
<%= form_for @user do |f| %>
  <%= f.collection_select :goal_ids, Goal.all, :id, :name, {}, { multiple: true } %>
  <%= f.submit %>
<% end %> 

迁移将包括:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.timestamps null: false
    end
    add_index :users, :email, unique: true

    create_table :goals do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :user_goals do |t|
      t.references :user
      t.references :goal
      t.string :choice
    end
  end
end