How do you update one object of a has_many :through relationship

Hi guys.

How do you update nested attributes for one object of a
has_many :through relationship? So I have an entity model and this
model can have many fact_values. The difference between fact and
fact_value is that the latter has an extra value attribute. This is
because facts can be common among many entities, but each entity can
have its own unique value for a specific fact. So my models are the
following:

class Entity
has_many :fact_values
has_many :facts, :through => :fact_values
end

class FactValue
belongs_to :entity
belongs_to :fact
end

class Fact
has_many :fact_values
has_many :entities, :through => :fact_values
end

Now I’ve specified that Entity
accepts_nested_attributes_for :fact_values. But I want it to accept
nested attributes for a single (pre-defined) fact_value and update
only that fact_value. The way I’m going about it right now is to have
a virtual attribute in my Entity model representing that one
fact_value and update that fact_value in the entity controller. I’m
wondering if there is any automatic way to accomplish what I’m trying
to do?

Thanks!

On Mon, Jun 14, 2010 at 1:55 AM, Ali [email protected] wrote:

class Entity
has_many :fact_values
to do?
Perhaps something along the lines of

class Entity

has_many :fact_values
has_many :facts, :through => :fact_values
belongs_to :anointed_fact_value

accepts_nested_attributes_for :fact_values, :reject_if =>
:not_updatable_fact_value

def not_updatable_fact_value(attrs)
attrs[:id] != anointed_fact_value_id
end
end


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

On Jun 14, 7:55 am, Ali [email protected] wrote:

I want it to accept nested attributes for a single (pre-defined)
fact_value and update only that fact_value

I’m not sure exactly what the problem is. If you only want to update
one object, you only put that object in the fields_for(:fact_values)
part of the form.
If you’re worried about the wrong object being created/updated through
accepts_nested_attributes, then the :reject_if can enable you to add
validation.

I’m using formtastic, I see that it seems simple enough with the
standard
rails forms. I suppose I can ask on a formtastic gorup to see what they
say.

Thanks