使用JSON通过

时间:2018-07-20 03:13:39

标签: ruby-on-rails reactjs rails-activestorage

我正在制作一个Rails API,在这里我想使用Active Storage将图像附加到帖子上,然后能够在REACT中访问它们,例如获取JSON中的url链接。如何将Active Storage映像转换为JSON的URL。有没有一种更好的方法可以获取到帖子图像的链接?

例如,我希望图像网址包含在此信息中:

发件人:http://localhost:3001/api/posts

[{"id":8,"title":"lolol","body":"lolol","created_at":"2018-07-19T23:36:27.880Z","updated_at":"2018-07-20T00:17:50.201Z","admin_user_id":1,"post_type":"Song","link":"dgdadg","song_title":"dgdadg","tag_list":[]},{"id":13,"title":"ddd","body":"dd","created_at":"2018-07-20T00:21:39.903Z","updated_at":"2018-07-20T00:21:39.907Z","admin_user_id":1,"post_type":"Song","link":"dddd","song_title":"ddd","tag_list":["Tag"]}]

这是我的后期控制者:

class PostsController < ApiController
    before_action :set_post, only: [:show, :update, :destroy]

  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag])
    else
      @posts = Post.all
    end

    render :json => @posts
  end

  def show
    @post
    render :json => @post
  end

  def create
    @post = Post.new(post_params)
  end

  def update
    @post.update(post_params)
    head :no_content
  end

  def destroy
    @post.destroy
    head :no_content
  end

  private

  def post_params
    params.require(:post).permit(:title, :body, :song_title, :post_type, :admin_user_id, :link, :tag_list, :image)
  end

  def set_post
    @post = Post.find(params[:id])
  end

end

任何建议将不胜感激。

3 个答案:

答案 0 :(得分:2)

大约2个星期前就去过那里,由于完全相同的问题而决定不使用ActiveStorage。您可以使用

做一些控制器魔术
while (state == 2) {
    if (ifcondtionismetbreak(someinput))
        break;
    cout << "Don't Print This When Condition Wants to Exit Loop\n";
}

喜欢

url_for(@post.image)

或类似的东西

render :json => @post.merge({image: url_for(@post.image)})

答案 1 :(得分:0)

如果您的AtomicReference<BigInteger>模型具有class A { private static final Object lock = new Object(); private static AtomicReference<BigInteger> staticCode = new AtomicReference<>(BigInteger.ZERO); public A() { BigInteger code; do { code = staticCode.get(); } while (!staticCode.compareAndSet(code, code.add(BigInteger.ONE))); this.code = code; // Even easier with AtomicInteger/Long: // this.code = BigInteger.valueOf(staticCode.incrementAndGet()); } } ,您可以致电 假设您的模型中有Post,则ActiveStorage::Attachment@post.file.service_url

答案 2 :(得分:0)

在jbuilder中可以访问url_for帮助器。因此您的_post.json.jbuilder可以像这样

json.extract! post, :id, :body, :created_at, :updated_at
if post.image.attached?
  json.image_url url_for(post.image)
end
json.url product_url(product, format: :json)