【问题标题】:Rails not saving modified attributesRails 不保存修改后的属性
【发布时间】:2016-12-27 22:04:07
【问题描述】:

我正在写一个降价博客,我想使用前端来定义元数据,例如帖子标题。前面的内容是 markdown 字段的一部分,并在控制器的 create 操作中进行解析。 我面临的问题是我的控制器拒绝保存修改后的属性。我已经尝试将其移入带有 before_actions 的模型方法中,但它不起作用。我也read this question 并在我的模型中尝试了attribute_will_change! 方法但没有成功。 我没有想法,所以任何帮助都将不胜感激。

  • 出于某种原因,public 属性按预期保存,但其余部分未保存。
  • 确保 fm 变量包含值(完美运行)
  • 尝试将其移动到模型 before_save 操作中
  • 我还尝试删除 ||= 并将其替换为常规的 = 分配。

后控制器创建

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

【问题讨论】:

    标签: ruby-on-rails activerecord markdown yaml-front-matter


    【解决方案1】:

    我使用符号而不是字符串访问了fm 变量...这就是问题所在。很烦人。

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 2013-04-25
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多