簡體   English   中英

不允許的參數,嵌套表單 - Ruby On Rails

[英]Unpermitted parameters , nested forms - Ruby On Rails

我已經按照 Michael Hartl 的教程進行操作,現在我想將照片添加到微博。 但是當我提交微博時,圖像沒有保存在數據庫中,並且在 dvlpmt 日志中我可以讀取未經許可的參數:image我查看了其他帖子並按照他們的建議進行了操作,但它對我不起作用。

楷模

微博.rb

class Micropost < ActiveRecord::Base
  belongs_to :user
  has_one :photo
  default_scope -> { order('created_at DESC') }
  validates :content, presence: true, length: { maximum: 140 }
  validates :user_id, presence: true
end

照片.rb

class Photo < ActiveRecord::Base
    belongs_to :micropost
    has_attached_file :image
end

控制器

照片控制器.rb

class PhotosController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy, :index]
  
  def create
    @photo = Photo.new(photo_params)

    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render action: 'static_pages/home', status: :created, location: @photo }
      else
        format.html { render action: 'static_pages/home' }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    def photo_params
      params.require(:photo).permit(:image)
    end
end

microposts_controller.rb

class MicropostsController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy]
  
  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end
  
  private

  def micropost_params
    params.require(:micropost).permit(:content, photo_attributes: [:photo_id, :image])
  end
end

意見

_micropost_form.html.erb我不知道如何構建這個表單,我嘗試了很多不同的公式

<%= form_for(@micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new micropost..." %>
  </div>

  <%= f.fields_for :image, :html => { :multipart => true } do |builder| %>
    <%= f.file_field :image, :f => builder %>
  <% end %>

  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

當我想提交我的表單時,沒關系,但是表微博的“photo_id”列是空的。 並且照片沒有保存在數據庫中。

服務器日志

Started POST "/microposts" for 127.0.0.1 at 2013-11-27 15:06:06 +0100
Processing by MicropostsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"<my_private_token>", "micropost"=>{"content"=>"Hello world", "image"=>#<ActionDispatch::Http::UploadedFile:0x00000003401a48 @tempfile=#<Tempfile:/tmp/RackMultipart20131127-4010-1r6qt80>, @original_filename="paint.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"micropost[image]\"; filename=\"paint.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Post"}
  [1m[36mUser Load (0.2ms)[0m  [1mSELECT "users".* FROM "users" WHERE "users"."remember_token" = '342df8f039f7f40698b3691f77d2539dc8b9c101' LIMIT 1[0m
Unpermitted parameters: image
  [1m[35m (0.1ms)[0m  begin transaction
  [1m[36mSQL (0.4ms)[0m  [1mINSERT INTO "microposts" ("content", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?)[0m  [["content", "Hello world"], ["created_at", Wed, 27 Nov 2013 14:06:06 UTC +00:00], ["updated_at", Wed, 27 Nov 2013 14:06:06 UTC +00:00], ["user_id", 101]]
  [1m[35m (145.1ms)[0m  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 153ms (ActiveRecord: 145.7ms)

我現在完全卡住了,如果你能找到可以幫助我在哪里找到解決方案的東西,謝謝!

您需要在Micropost課程中使用accepts_nested_attributes_for

class Micropost < ActiveRecord::Base
  belongs_to :user
  has_one :photo
  accepts_nested_attributes_for :photo
  default_scope -> { order('created_at DESC') }
  validates :content, presence: true, length: { maximum: 140 }
  validates :user_id, presence: true
end

看起來您的表單將圖像與您的微博相關聯,而不是與微博的照片相關聯。 查看fields_for的 Ruby 文檔。 您可以嘗試將表格的一部分更改為此嗎?

<%= f.fields_for :photo, :html => { :multipart => true } do |photo_fields| %>
  <%= photo_fields.file_field :image %>
<% end %>

如果您這樣做,您需要確保在呈現視圖的控制器操作中調用@micropost.build_photo

我認為您不需要在microposts_controller.rb的強參數中列出photo_id 一旦記錄保存到數據庫,就應該設置它。

您還可以閱讀有關構建復雜表單的 Rails 指南。 該指南討論了如何設置模型、視圖和控制器來處理嵌套屬性。 如果您還沒有,他們對強參數的描述可能有助於檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM