Question

I have a model A that "has many" B.

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :title
end
class B < ActiveRecord::Base
  belongs_to :A
  attr_accessible :name
end

I want to add a field to my "edit A" form : a textarea in which I will enter my B's :name for each line, and on submit, parse the field, and process each line.

The question is, how should I do that ?

Edit

Following Rails - Add attributes not in model and update model attribute I have come to this :

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :title

  def my_b
    list = ""
    self.B.each do |b|
      list += "#{b.name}\n"
    end
    logger.debug("Displayed Bs : " + list)
    list
  end

  def my_b=(value)
    logger.debug("Saved Bs : " + value)
    # do my things with the value
  end

end

But def bees=(value) never seems to be fired.

What am I doing wrong ?

Edit 2

My actual code is visible here : https://github.com/cosmo0/TeachMTG/blob/edit-deck/app/models/deck.rb

Was it helpful?

Solution 2

Oh my. Turns out the problem was not lying in the model, but in the controller... I forgot to add a simple line in the update method to assign my POST value to my class field...

Anyway, final solution is this :

In my controller :

  def update
    @a.whatever = params[:a][:whatever]
    @a.my_b = params[:a][:my_b]
    @a.save
  end

In my model :

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :whatever

  def my_b
    list = ""
    self.B.each do |b|
      list += "#{b.name}\n"
    end
    list
  end

  def my_b=(value)
    # parse the value and save the elements
  end
end

OTHER TIPS

You can put an :attr_accessor, like:

class A < ActiveRecord::Base
  has_many :B
  attr_accessible :title
  attr_accessor :field_of_happiness

  def field_of_happiness=(value)
    # override the setter method if you want 
  end

  def field_of_happiness(value)
    # override the getter method if you want 
  end
end

Reference: attr_accessor api doc

It helps you on some way?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top