0

I have two classes (Game and Report) and want to link them with an additional attribute (default = yes or no). The game should then have default_reports and optional_reports. The association is then updated by selecting the default and optional reports in a select (multiple) in the games create/edit form.

I have tried using has_many and through as well as polymorphic associations, but nothing seems to fit the use case, where the associated objects are fixed and you only want to manage associations.

class Game < ActiveRecord::Base
  has_many :game_reports
  has_many :reports, :through => :game_reports
end

class Report < ActiveRecord::Base
  has_many :game_reports
  has_many :games, :through => :game_reports
end

class GameReport < ActiveRecord::Base
  belongs_to :game
  belongs_to :report
end

Any help is appreciated!

Thanks

2 Answers2

0

this is just the model. the view and form to create the records is an entirely different matter.

you can always add a conditions option to has_many. I'm assuming you're going to add default to game_reports so change your class to something like.

class Game < ActiveRecord::Base
  has_many :game_reports
  has_many :reports, :through => :game_reports
  has_many :default_reports, through: :game_reports, source: :report, conditions: { game_reports: { default: true } }
end
jvnill
  • 29,479
  • 4
  • 83
  • 86
  • Yeah, thanks. I was nearly that far. I would like to not change the games controller at all, just select some reports (and send their report.id) and handle the associations automatically. There should be a rails way?! The form field for the multiple select looks like this: <%= f.select :required_reports, options_for_select(Report.all.map {|r| [r.name, r.id]}, @game.required_reports.map {|rr| rr.id}), {}, {:multiple => true} %> This results in a params string like this: {:game => {"required_reports"=>["", "2"]},..} update error: Report(#11316) expected, got String(#11318) – user2087456 Feb 19 '13 at 16:11
  • nearly there: using <%= f.select :default_report_ids, Report.all.collect {|x| [x.name, x.id]}, {}, :multiple => true %> right now and the maybe last problem is, that the GameReport validation fails because the required (default oroptional) boolean value is not set. Do I have to manually insert that into the params hash or is there a better way to add this attribute? – user2087456 Feb 19 '13 at 16:30
0

Rails 4.2+, use a Polymorphic association with scope and specify the foreign_key and foreign_type options.

class GameReport
   belongs_to :report, :polymorphic => true
end

class Game
   has_many :game_reports, :as => :report, :dependent => :destroy
   has_many :reports, -> { where attachable_type: "GameReport"},
     class_name: GameReport, foreign_key: :game_report_id,
     foreign_type: :game_report_type, dependent: :destroy
end

Other approachs:

Rails Polymorphic Association with multiple associations on the same model

Community
  • 1
  • 1
Bmxer
  • 397
  • 1
  • 3
  • 9