Witam, jak mozna w RoR wyciagnac dane z tabeli posredniczacej w relacji many-to-many w przypadku tj ponizej:
[code]create_table “casts”, :id => false do |t|
t.integer “star_id”, :null => false
t.integer “movie_id”, :null => false
t.string “role”
end
class Star < ActiveRecord::Base
has_many :casts
has_many :movies, :through => :casts
end
class Movie < ActiveRecord::Base
has_many :casts
has_many :stars, :through => :casts
end
class Cast < ActiveRecord::Base
belongs_to :movie
belongs_to :star
end[/code]
Teraz jak np z widokow Movie dostac sie do danych zawartych w casts.role dla konkretnego Star, tj:
<% for star in @movie.stars %>
<%= star.name %> <%= star.age %> - <%= star.?????????.role %>,
<% end %>
Domyslam sie ze pewnie rozwiazania nie da sie wcisnac w miejsca ??? no ale wlasciwie bede wdzeczny za kazda poprawna koncepcje
[code]ActiveRecord::Schema.define(:version => 20090117190259) do
create_table “casts”, :force => true do |t|
t.integer “star_id”
t.integer “movie_id”
t.datetime “created_at”
t.datetime “updated_at”
t.integer “role_id”
end
create_table “movies”, :force => true do |t|
t.datetime “created_at”
t.datetime “updated_at”
end
create_table “roles”, :force => true do |t|
t.string “name”
t.datetime “created_at”
t.datetime “updated_at”
end
create_table “stars”, :force => true do |t|
t.datetime “created_at”
t.datetime “updated_at”
end
end
class Cast < ActiveRecord::Base
belongs_to :movie
belongs_to :star
belongs_to :role
end
class Movie < ActiveRecord::Base
has_many :casts
has_many :stars, :through => :casts
end
class Role < ActiveRecord::Base
has_many :casts
end
class Star < ActiveRecord::Base
has_many :casts
has_many :movies, :through => :casts
end[/code]
forum_test4> m = Movie.first
SQL (0.1ms) SET NAMES 'utf8'
SQL (0.1ms) SET SQL_AUTO_IS_NULL=0
Movie Load (0.2ms) SELECT * FROM `movies` LIMIT 1
Movie Columns (1.8ms) SHOW FIELDS FROM `movies`
=> #<Movie id: 1, created_at: "2009-01-17 18:46:21", updated_at: "2009-01-17 18:46:21">
forum_test4> m.stars
Star Load (0.4ms) SELECT `stars`.* FROM `stars` INNER JOIN casts ON stars.id = casts.star_id WHERE ((`casts`.movie_id = 1))
Star Columns (2.1ms) SHOW FIELDS FROM `stars`
=> [#<Star id: 1, created_at: "2009-01-17 18:46:41", updated_at: "2009-01-17 18:46:41">]
forum_test4> s = m.stars[0]
=> #<Star id: 1, created_at: "2009-01-17 18:46:41", updated_at: "2009-01-17 18:46:41">
forum_test4> s.casts
Cast Load (0.4ms) SELECT * FROM `casts` WHERE (`casts`.star_id = 1)
Cast Columns (2.4ms) SHOW FIELDS FROM `casts`
=> [#<Cast id: 1, star_id: 1, movie_id: 1, created_at: "2009-01-17 18:46:50", updated_at: "2009-01-17 19:07:24", role_id: 1>]
forum_test4> s.casts[0].role
Role Columns (2.1ms) SHOW FIELDS FROM `roles`
Role Load (0.3ms) SELECT * FROM `roles` WHERE (`roles`.`id` = 1)
=> #<Role id: 1, name: "dupa", created_at: "2009-01-17 19:02:19", updated_at: "2009-01-17 19:02:19">
forum_test4> s.casts[0].role.name
=> "dupa"