【问题标题】:Add new field to index.json in Rails 4在 Rails 4 中向 index.json 添加新字段
【发布时间】:2014-10-23 08:59:32
【问题描述】:

我想在我的 index.json 中添加一个修改过的变量。

views/posts/index.json.builder

json.array!(@posts) do |post|
  post[:image_th] = post[:image].reverse.split('.', 2).join(".s").reverse
  #this is the new line above

  json.extract! post, :id, :title, :datum, :body, :image
  #json.url post_url(post, format: :json)
end

所以它会在字符串中的“.jpg”之前添加一个's'。

这给出了错误:

无法写入未知属性`image_th'

如何在不创建迁移并从数据库访问它的情况下向 index.json 添加字段?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4


    【解决方案1】:

    试试:

    class Post < ActiveRecord::Base
      # ...
    
      def image_th
        image.reverse.split('.', 2).join(".s").reverse
      end
    
    end
    

    然后:

    json.extract! post, :id, :title, :datum, :body, :image_th
    

    编辑:

    此外,该方法可能会稍微干净一些:

    def image_th
      image.sub(/\.[^\.]+$/, 's\0')
    end
    

    【讨论】:

    • 我怎么没想到呢?谢谢! :)
    • 感谢您的方法!
    【解决方案2】:

    如果您不需要持久化它,您可以在 Post 模型中使用 attr_accessor :image_th

    class Post < ActiveRecord::base
      attr_accessor :image_th
    end
    

    在你的模型中声称更多的是一种方法而不是一个字段

    【讨论】:

    • 这是 rails4,那里没有 attr_accessor。
    猜你喜欢
    • 2015-08-12
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多