Ruby on rails 如何在Rails中使用has\u和\u-belish\u-to\u-many保存额外字段
我的rails应用程序具有以下结构:Ruby on rails 如何在Rails中使用has\u和\u-belish\u-to\u-many保存额外字段,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我的rails应用程序具有以下结构: class Movie < ActiveRecord::Base has_and_belongs_to_many :celebs, :join_table => "movies_celebs" end class Celeb < ActiveRecord::Base has_and_belongs_to_many :movies, :join_table => "movies_celebs" end class MovieCe
class Movie < ActiveRecord::Base
has_and_belongs_to_many :celebs, :join_table => "movies_celebs"
end
class Celeb < ActiveRecord::Base
has_and_belongs_to_many :movies, :join_table => "movies_celebs"
end
class MovieCeleb < ActiveRecord::Base
belong_to :movie
belong_to :celeb
end
class电影“电影\u名人”
结束
类Celeb“电影\u名人”
结束
类MovieCeleb
现在MovieCeleb有两个额外的字段CastName(string)、CastType('Actor/Director)。当我保存电影时,我也会创建名人,并将名人填入名人关系,它会自动将电影和名人保存到数据库中。但是我如何传递CastName和CastType来保存呢
请告知
提前感谢。如果您需要验证、回调或连接模型上的额外属性,您应该使用has\u many:through而不是has\u和\u-belies\u-to\u many 见:
注意,以下内容适用于Rails v2
script/generate model Movie id:primary_key name:string
script/generate model Actor id:primary_key movie_id:integer celeb_id:integer cast_name:string cast_type:string
script/generate model Celeb id:primary_key name:string
model/movie.rb
class Movie < ActiveRecord::Base
has_many :actors
has_many :celebs, :through => :actors
end
model/celeb.rb
class Celeb < ActiveRecord::Base
has_many :actors
has_many :movies, :through => :actors
end
model/actor.rb
class Actor < ActiveRecord::Base
belongs_to :movie
belongs_to :celeb
end
然后你可能会想看看Ryan Bates的Railcast#47(两个多对多)和#73、#74、#75(复杂形式第1-3部分)
在#75的网页上有一个多对多表单代码的更新版本。我正在学习ruby on rails。你能给出一个示例代码吗?使用has_many:through保存数据的最佳方法是什么?单击链接并查看示例。如果你使用has_多:通过代替h_a_b_t_m,你得到两个关系,而不是一个,与电影名人的关系和与电影名人的关系。因此,您可以在movie_celeb关系模型中读取/写入属性。
>script/console
>m = Movie.new
>m.name = "Do Androids Dream Of Electric Sheep"
>m.methods.sort #this will list the available methods
#Look for the methods 'actors' and 'celebs' - these
#are the accessor methods built from the provided models
>m.actors #lists the actors - this will be empty atm
>c = Celeb.new
>c.name = "Harrison Ford"
>m.celebs.push(c) #push Harrison Ford into the celebs for Blade Runner
>m.actors #Will be empty atm because the movie hasnt been saved yet
>m.save #should now save the Movie, Actor and Celeb rows to relevant tables
>m.actors #Will now contain the association for
#Movie(id : 1, name : "Do Androids..") - Actor(id : 1, movie_id : 1, celeb_id : 1) -
#Celeb(id : 1, name : "Harrision Ford")
>m = Movie.new #make a new movie
>m.name = "Star Wars"
>m.celebs.push(c) #associated the existing celeb with it
>m.save
>movies = Movie.all #should have the two movies saved now
>actors = Actor.all #should have 2 associations
>this_actor = Actor.first
>this_actor.cast_type = "ACTOR"
>this_actor.save