【问题标题】:Get json response from "create" function in rails 5从rails 5中的“create”函数获取json响应
【发布时间】:2017-02-18 08:43:20
【问题描述】:
  # GET /posts/new
  def new
    @post = Post.new
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

我只想知道如何让“def create”在保存帖子后返回 show.json.builder

这是我将信息发送到“def create”的表单,我已经尝试添加属性:“data-type”=>“json”,但它不起作用,并通过方法 POST 调用使用“/posts.json”操作,它不会调用“create”函数,只是在我发送时显示包含对象帖子的所有信息

 <%= form_for post do |f| %>


     <div class="field">
        <%= f.label :title %>
        <%= f.text_field :title %>
      </div>

      <div class="field">
        <%= f.label :body %>
        <%= f.text_area :body %>
      </div>

      <div class="actions">
        <%= f.submit %>
      </div>


 <% end %>

【问题讨论】:

    标签: ruby-on-rails json format ruby-on-rails-5


    【解决方案1】:

    这样试试

     <%= form_for(@post, format: :json) do |f| %>
    
        ----
    

    http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for

    此外,如果您希望使用 ajax 处理,您应该考虑添加 remote: true。

    【讨论】:

    • 你救了我!!!我之前尝试使用 html: {:format => 'json'} 并没有用,你为什么?
    • 我不确定,也许他们正在阅读旧 Rails 版本上的文档/教程,这些文档/教程不再正确
    猜你喜欢
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    相关资源
    最近更新 更多