0

私は、ユーザーがDeviseを介してサインアップし、他の人が投票できるように写真を投稿できるWebアプリを持っています。

ユーザーがアップロードする写真にユーザー名を添付しようとしていますが、その方法を一生理解できません。

Deviseのuser_idを非表示のフィールドからフォームに取り込む方法を理解しましたが、ユーザー名はデータベースに空白のフィールドとして表示されます(空白ではありませんNULL)。

user_idの代わりにDeviseから投稿するユーザー名を取得するにはどうすればよいですか?

私はすべての適切なbelongs_toモデルhas_manyを持っています。

フォーム。

<% if current_user %>
    <%= simple_form_for Picture.new, :remote => true, :html => { :class => "form-horizontal" } do |f| %>
    <%= f.input :title %>
    <%= f.input :image, :as => :image_preview, :label => false, :input_html => {:preview_version => :thumb} %>
      <div class="control-group"> 
        <div class="controls">
          <a href="#" class="btn" id="file">Choose a File</a>
        </div>
      </div>
      <%= f.input :desc, :as => :text, :input_html => { :cols => 20, :rows => 3 }, :label => 'Description' %>
      <%= f.hidden_field :user_id %>
      <%= f.hidden_field :username %>
      <div class="control-group">
        <div class="controls">
          <div class="btn-group">
            <%= f.submit "Add Picture", :class => 'btn btn-primary' %>
            <button class="btn btn-danger" id="form-cancel">Cancel</button>
        </div>
      </div>
    <% end %>

pictures_controller.rb

def create  
  #This line inserts the user_id into the database
  @picture = current_user.pictures.create!(params[:picture])  
  @picture.save  
    respond_to do |format|  
      format.html { redirect_to pictures_url, notice: 'Thanks for your picture!' }  
      format.js  
    end  
end   
4

1 に答える 1

2

隠しフィールドは必要ありません。非表示フィールドを使用すると、セキュリティリスクも追加されます。ユーザーは画像をアップロードして、別のユーザーがアップロードしたように見せることができます。現在のユーザーのIDとユーザー名を画像に追加するには、次のようにコントローラーを変更するだけです。

@picture = Picture.new(params[:picture])
@picture.user_id = current_user.id
@picture.username = current_user.username # assuming the user model has a username field
@picture.save

より良い方法は、ユーザーのIDを画像とともに保存し、ユーザー名を画像とともに保存するのではなく、画像モデルが持っていることbelongs_to :userとユーザーモデルが持っていることを確認することです。has_many :picturesこのメソッドを使用してユーザー名を取得する場合は、次の方法でアクセスできます。picture.user.username

于 2012-11-01T14:49:01.617 に答える