werm
werm

Reputation: 458

Rails - Add Devise user info to post

I have a web app where users can sign up, via Devise, and post pictures for other people to vote on.

I'm trying to attach the users username to the photo that they upload, but I can't for the life of me figure out how.

I figured out how to get the Devise user_id into the form through a hidden field, but the username just shows up in the database as a blank field (not NULL, just blank).

How do I get the username from Devise to post instead of the user_id?

I have all of the appropriate belongs_to and has_many in the models.

The form.

<% 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   

Upvotes: 0

Views: 949

Answers (1)

Tomdarkness
Tomdarkness

Reputation: 3820

You don't need the hidden fields. Using hidden fields also adds a security risk, a user could upload a picture and make it appear that it was uploaded by another user. To add the current user's id and username to the picture then all you need to do is modify your controller as follows:

@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

Although a better way would be to just store the user's id with the picture and make sure the pictures model has belongs_to :user and the users model has has_many :pictures, rather than storing the username with the picture. Using this method when you want to fetch the username you can access it via picture.user.username

Upvotes: 2

Related Questions