Rails 4关联回调通过模型更新

时间:2014-07-22 06:36:46

标签: ruby-on-rails ruby activerecord ruby-on-rails-4 ruby-on-rails-3.1

我有3个模特"电影","人"," MoviePerson"

查看这些模型的有效记录

movie.rb

class Movie < ActiveRecord::Base
  has_many :movie_persons
  has_many :persons, through: :movie_persons

  has_many :directors, -> { where 'movie_people.type =? ', "Director" }, through: :movie_persons, :foreign_key => :person_id, :class_name => "Person", :source => :person
  has_many :music, -> { where 'movie_people.type =? ', "Music" }, through: :movie_persons, :foreign_key => :person_id, :class_name => "Person", :source => :person
end

person.rb

class Person < ActiveRecord::Base
  has_many :movie_persons
  has_many :movies, through: :movie_persons
end

movie_person.rb

class MoviePerson < ActiveRecord::Base
    self.inheritance_column = :_type_disabled

    belongs_to :movie
    belongs_to :person
end

在rails控制台

2.0.0p247 :011 > m = Movie.last
 Movie Load (0.7ms)  SELECT  "movies".* FROM "movies"   ORDER BY "movies"."id" DESC LIMIT 1
  => #<Movie id: 7501, name: "Test", genre: [], status: "", shooting_location: [], plot: "", keyword: [], release_date: nil, url: nil, song_url: nil, created_at: "2014-07-22 03:58:48", updated_at: "2014-07-22 03:58:48"> 

2.0.0p247 :012 > m.director_ids = [Person.last.id]
Person Load (0.7ms)  SELECT  "people".* FROM "people"   ORDER BY "people"."id" DESC LIMIT 1
Person Load (0.5ms)  SELECT  "people".* FROM "people"  WHERE "people"."id" = $1 LIMIT 1  [["id", 20685]]
Person Load (18.9ms)  SELECT "people".* FROM "people" INNER JOIN "movie_people" ON "people"."id" = "movie_people"."person_id" WHERE (movie_people.type ='Director' ) AND "movie_people"."movie_id" = $1  [["movie_id", 7501]]
(0.2ms)  BEGIN
#<Person id: 20685, name: "Yansi", bod: nil, bio: nil, url: "", created_at: "2014-06-21 13:53:36", updated_at: "2014-06-21 13:53:36">
SQL (0.5ms)  INSERT INTO "movie_people" ("created_at", "movie_id", "person_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", "2014-07-22 06:25:17.279331"], ["movie_id", 7501], ["person_id", 20685], ["updated_at", "2014-07-22 06:25:17.279331"]]
(9.5ms)  COMMIT
=> [20685]

2.0.0p247 :013 > m.director_ids
=> [] 

此处m.director_ids返回空数组,因为没有将 movie_person 的类型更新为导演

如何使用关联回调解决此问题?

0 个答案:

没有答案