新手需要一些帮助来建立表之间的关系

时间:2015-07-09 09:13:18

标签: ruby-on-rails ruby database

大家好,我是红宝石的新手,我需要一些帮助: 我在ruby中设置了三个表,以下是模型:

班级用户:

 coding: utf-8

class User < ActiveRecord::Base
    validates :password, presence: true, confirmation: {strict: true}
    validates :password_confirmation, presence: true
    validates :telephone, uniqueness: true, presence: true, numericality: { only_integer: true }, presence: true, length: { minimum: 9, maximum: 9 }
    validates :name, presence: true, length: { minimum: 4, maximum: 30 }, format: { with: /^[\w\s-]*/u, multiline: true,
                                                                              message: 'only allows letters' }
   has_many :users_valorations
   has_many :valoraions, through: :users_valorations
end

阶级价值:

class Valoration < ActiveRecord::Base
   validates :points, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 100 }
   validates :category, presence: true, length: { minimum: 4, maximum: 30 }, format: { with: /\A[a-zA-Z\ ]+\z/,
                                                                              message: 'only allows letters' }
   has_many :users_valorations
   has_many :users, through: :users_valorations
end

Class UsersValoraion

class UsersValoration < ActiveRecord::Base
   belongs_to :user
   belongs_to :valoration
end

schema.rb:

  ActiveRecord::Schema.define(version: 20150708212501) do

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.integer  "telephone"
    t.string   "password"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users_valorations", force: :cascade do |t|
    t.integer  "valoration_sender_id"
    t.integer  "valoration_target_id"
    t.datetime "created_at",           null: false
    t.datetime "updated_at",           null: false
  end

  add_index "users_valorations", ["valoration_sender_id"], name: "index_users_valorations_on_valoration_sender_id"
  add_index "users_valorations", ["valoration_target_id"], name: "index_users_valorations_on_valoration_target_id"

  create_table "valorations", force: :cascade do |t|
    t.integer  "points"
    t.string   "category"
    t.datetime "time"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

所有类都是由脚手架生成的,现在我只想做到这一点:

- &gt;当您创建valoration时,您必须选择谁发送它以及谁将接收它,并且该数据将保存在UsersValoration表中 - &gt;列出所有的valorations以及发送它们的用户的链接。

我很新,所以欢迎任何帮助

1 个答案:

答案 0 :(得分:0)

据我了解您的问题,您需要在创建UserValoration之前或之后进行操作。

ActiveRecord提供回调以在对象生命周期中执行某些操作。您可以在此处找到更多信息:http://guides.rubyonrails.org/active_record_callbacks.html