Rails 5 - Acts as Taggable On with predefined tags

411 views Asked by At

I'm trying to use the acts as taggable on gem with my rails 5 app.

I have a model called Proposal, which I'm trying to tag with predefined tags from my Randd::Fields model.

In my proposal.rb, I have:

class Proposal < ApplicationRecord

  acts_as_taggable
  acts_as_taggable_on :randd_maturities, :randd_fields, :randd_purposes, :randd_activities

In my proposal controller, I have whitelisted the randd_fields_list attribute:

params.require(:proposal).permit(:title, :randd_fields_list)

In my Randd::Fields table, I have one record saved:

Randd::Field.all
  Randd::Field Load (0.5ms)  SELECT "randd_fields".* FROM "randd_fields"
 => #<ActiveRecord::Relation [#<Randd::Field id: 1, created_at: "2016-11-26 08:38:11", updated_at: "2016-11-26 08:38:11", anz_reference: "test ref", title: "test title">]> 

In the console, I'm trying to add the predefined Randd::Field.title to the proposal:

Proposal.first.randd_field_list.add(Randd::Field.find_by(id: 1).title)

But - then when I try: Proposal.first.randd_field_list, I get:

p.randd_field_list
  ActsAsTaggableOn::Tagging Load (0.7ms)  SELECT "taggings".* FROM "taggings" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2  [["taggable_id", 17], ["taggable_type", "Proposal"]]
  ActsAsTaggableOn::Tag Load (0.9ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'randd_fields' AND taggings.tagger_id IS NULL)  [["taggable_id", 17], ["taggable_type", "Proposal"]]
 => [] 

So - that hasn't worked.

How do I make the randd_field_list update with my defined tags in the Randd::Field table?

1

There are 1 answers

0
Alex Kojin On BEST ANSWER

To save tag you need to save Proposal object:

proposal = Proposal.first
proposal.randd_field_list.add(Randd::Field.find_by(id: 1).title)
proposal.save