Kuf
Kuf

Reputation: 17828

Rails set has_many value dynamically

I have an entity: book of class Book.

The entity class has has_many relation with other tables, pages for example.

Let's say that page_1 and page_2 are valid values that I'de like to save. The non-dynamic version would be something like:

entity.pages = [page_1, page_2]

How can I set this dynamically?

I tried using send (which works fine for has_one) with no luck:

attr = :pages # my dynamic attribute 

book.send(attr) = [page_1, page_2]
# SyntaxError: unexpected '=', expecting end-of-input
# mc.send(:diagnoses, '=') = [s]
#                           ^

When I use << it seems to work:

book.send(attr) << page_1

but the issue is that I need to support deletion, e.g. if the book had page3, and now it has page1 and page2.

I don't want to use eval, both due to performance and security. Not sure it's related, but these dynamic attributes all have the same class - has__many with a dynamic condition.

Upvotes: 0

Views: 466

Answers (2)

user8018795
user8018795

Reputation: 46

Try book.association(:pages).target

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

The correct format is to call the setter (assignment) method. Which is usually the attribute followed by an equal sign. In your case, you want pages=

book.send(attr.to_s + '=', [page_1, page_2] )

Equivalent to

book.send('pages=', [page_1, page_2])

which is...

book.pages=([page_1, page_2])

or more conventionally written

book.pages = [page_1, page_2]

Upvotes: 2

Related Questions