私は、ユーザーが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