Updating extra attributes in a has_many, :through relationship using Rails

Posted by Robbie on Stack Overflow See other posts from Stack Overflow or by Robbie
Published on 2010-06-14T05:12:15Z Indexed on 2010/06/14 5:22 UTC
Read the original article Hit count: 372

I've managed to set up a many-to-many relationship between the following models

  • Characters
  • Skills
  • PlayerSkills

PlayerSkills, right now, has an attribute that Skills don't normally have: a level.

The models look something like this (edited for conciseness):

class PlayerSkill < ActiveRecord::Base
  belongs_to :character
  belongs_to :skill
end

class Skill < ActiveRecord::Base
  has_many :player_skills
  has_many :characters, :through => :player_skills

  attr_accessible :name, :description
end

class Character < ActiveRecord::Base
  belongs_to :user

  has_many :player_skills
  has_many :skills, :through => :player_skills
end

So nothing too fancy in the models... The controller is also very basic at this point... it's pretty much a stock update action.

The form I'm looking to modify is characters#edit. Right now it renders a series of checkboxes which add/remove skills from the characters. This is great, but the whole point of using has_many :through was to track a "level" as well.

Here is what I have so far:

- form_for @character do |f|
  = f.error_messages
  %p
    = f.label :name
    %br
    = f.text_field :name
  %p
    = f.label :race
    %br
    = f.text_field :race
  %p
    = f.label :char_class
    %br
    = f.text_field :char_class
  %p
    - @skills.each do |skill|
      = check_box_tag "character[skill_ids][]", skill.id, @character.skills.include?(skill)
      =h skill.name
      %br
  %p
    = f.submit

After it renders "skill.name", I need it to print a text_field that updates player_skill.

The problem, of course, is that player_skill may or may not exist! (Depending on if the box was already ticked when you loaded the form!)

From everything I've read, has_many :through is great because it allows you to treat the relationship itself as an entity... but I'm completely at a loss as to how to handle the entity in this form.

As always, thanks in advance for any and all help you can give me!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord