I am writing a markdown blog and I want to use front matter to define meta data such as post titles. This front matter is part of the markdown field and is parsed in the controller's create action.
The issue I am facing is that my controller refuses to save the modified attributes. I have tried moving this into a model method with before_actions which didn't work. I've also read this question and tried the attribute_will_change!
method in my model without success.
I am out of ideas so any help would be appreciated.
- For some reason, the
public
attribute is saved as expected but the rest is not. - made sure that the fm variable contains values (works flawlessly)
- tried moving this into a model before_save action
- I've also tried removing the
||=
and replacing them with regular=
assignment.
Post Controller Create
def create
@post = Post.new(post_params)
@post.public = true
@post.user = User.first
@post.word_count = @post.markdown.scan(/[\w-]+/).size
fm, content = YAML::FrontMatter.extract(@post.markdown)
@post.title_will_change!
@post.title ||= fm[:title].to_s
@post.subtitle ||= fm[:subtitle]
@post.abstract ||= fm[:abstract]
@post.video_token ||= fm[:video_token]
@post.slug ||= fm[:slug]
@post.seo_keywords = fm[:seo_keywords]
if @post.image
@post.image_id = fm[:image]
end
cat = Category.find_by_name(fm[:category])
if cat.present?
@post.category = cat
else
@post.category = Category.create(name: fm[:category])
end
new_markdown = @post.markdown.gsub(/(---\n(?:.*: '.*'\n)*---)/, '')
@post.markdown = new_markdown
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, locataion: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end