Cuộc sống Nhật Bản
Yuto Blog

【 Ruby on Rails】Hướng dẫn sử dụng ActionText

Mua ngay trả dần cùng Muadee iOS
Nội dung chính
【 Ruby on Rails】Hướng dẫn sử dụng ActionText

Cài đặt ActionText


rails action_text:install

rake db:migrate

Không cần phải có column "content" trong table articles

app/models/article.rb
has_rich_text :content
validates :content, presence: true, length: { minimum: 5 }

app/controllers/articles_controller.rb
def article_params
  params.require(:article).permit(:content)
end

app/views/articles/_form.html.slim
= f.label :content
= f.rich_text_area :content

app/views/articles/show.html.slim
== @article.content

Customize style


app/javascript/src/application.scss
@import "trix/dist/trix";
@import "../../assets/stylesheets/actiontext";

app/assets/stylesheets/actiontext.scss
trix-editor {
  min-height: 500px;
  height: auto !important;
  overflow: auto;

  blockquote {
    font-style: italic;
    margin-left: 20px;
    padding-left: 20px;
    border-left: 5px solid lightgray;
  }

  pre {
    font-family: 'Courier New';
    background-color: lightgray;
  }
}

trix-toolbar {
  // Important: position sticky is not work if the parent have overflow attribute
  position: sticky;
  top: 0;
  background: #FFFFFF;
  z-index: 999;
}

.trix-content {
  .attachment-gallery {
    > action-text-attachment,
    > .attachment {
      flex: 1 0 33%;
      padding: 0 0.5em;
      max-width: 33%;
    }

    &.attachment-gallery--2,
    &.attachment-gallery--4 {
      > action-text-attachment,
      > .attachment {
        flex-basis: 50%;
        max-width: 50%;
      }
    }
  }

  action-text-attachment {
    .attachment {
      padding: 0 !important;
      max-width: 100% !important;
    }
  }

  h1 {
    font-size: 1.8em;
  }

  pre {
    font-family: 'Courier New';
    background-color: lightgray;
  }
}

Use image


Gemfile
gem 'image_processing'


Trường hợp AWS không upload được hình ảnh thì setting CORS như sau:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>


Trix extensions

https://github.com/lazaronixon/trix-extensions
Thêm chỉnh màu sắc, 6 thẻ heading và hr

Lưu ý setting trong file config/environments/production.rb
config.assets.compile = true
Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé
Rate this article: 5/5 (16 ratings)
You didn't rate yet
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.