Rails: ActionText has_rich_text returns nil

1k Views Asked by At

I've added ActionText into my Rails 5.2 app, according to this tutorial. I performed installation, migration and added action_text_rich_texts column. I also updated my model:

class LiveEvent < ApplicationRecord
  has_rich_text :description_long
end 

However has_rich_text helper seems to not working. When I try to initialize new record this way:

@live_event = LiveEvent.new(live_event_params)

description_long attribute returns nil because of this helper. Which crashes my app due to the validation constrains.

Strong param permission for description_long it's also not a case since that attribute was permitted before. This error occurs even if I want to add new record directly through the Rails console:

le = LiveEvent.new(description_long: 'test')
le[:description_long] // returns nil

Maybe there is no established binding between action_text_rich_texts and my LiveEvent model? I'm not sure what it the possible cause of this error. How can I fix it?

1

There are 1 best solutions below

0
On BEST ANSWER

ActionText is providing polymorphic association with Model we mention has_rich_text.

So when we define has_rich_text is actually we are defining an association, like we do has_one, 'has_many', belongs_to.

So when you write

@live_event = LiveEvent.new(description_long: 'test')

It will create a new instance of ActionText::RichText model and assign the "text" in the body column as instance of ActionText::Content. So what ever value we assigned to description_long as rich text will automatically wrapped into into a div tag <div class="trix-content">.

Here is the example.

pry(main)> e = Email.new(content: "Asd")
=> #<Email:0x00007fd612746018
 id: nil,
 user_id: nil,
 subject: nil,
 created_at: nil,
 updated_at: nil>

pry(main)> e.content
=> #<ActionText::RichText:0x00007fd612745c80
 id: nil,
 name: "content",
 body: #<ActionText::Content "<div class=\"trix-conte...">,
 record_type: "Email",
 record_id: nil,
 created_at: nil,
 updated_at: nil>

pry(main)> e[:content]
=> nil

pry(main)> e.content.body.to_s
=> "<div class=\"trix-content\">\n  Asd\n</div>\n"

so content in this example is not actually a column but it's a association. same way description_long in your example is an association not a column.

Please fine the note below "Note: you don't need to add a content field to your messages table." here in this guide https://edgeguides.rubyonrails.org/action_text_overview.html