0

I have a table in the database called pcomment. Each pcomment belongs_to a purchase. A purchase has_many pcomments. additionally, each user has_many pcomments and each pcomment belongs_to user. In the database, the pcomments table has id/user_id/purchase_id/body/created_at/updated_at

Everything is getting filled in correctly except for user_id is still always blank. I want it to be filled in with the user_id of the current signed in user (ie the one who is creating the pcomment.) Both the user_id and pcomment_id are indexed in the table with add_index (during the migration)

Here is the form for the pcomment

  <%= form_for([purchase, purchase.pcomments.build]) do |f| %>

    <div class="field">
      <h4>What deal are you offering?</h4>
      <%= f.text_field :body %>


    </div>


  <% end %>

Here is the pcomments_controller.rb

class PcommentsController < ApplicationController
  before_filter :signed_in_user
  def create
    @purchase = Purchase.find(params[:purchase_id])
    @pcomment = @purchase.pcomments.build(params[:pcomment])

    @pcomment.purchase = @purchase

    if @pcomment.save
       flash[:success] = "Offer submited!"
       redirect_to :back
    else
      render 'shared/_pcomment_form'
    end
  end

  def new
@pcomment=purchase.pcomments.new

  end


end

If you need more of my code it is at https://github.com/tradespring1/tradespring/

klondike-5-3226
  • 171
  • 1
  • 1
  • 9

1 Answers1

0

This probably isn't the best way to do it, but if you've defined a "current_user" method, or are using devise you can simply put @pcomment.user_id = current_user.id right before @pcomment.save

Abram
  • 39,950
  • 26
  • 134
  • 184
  • no way. I have trying to fix this for over 20 hours. Your way finally worked. I really appreciate this – klondike-5-3226 Oct 13 '12 at 02:30
  • Glad it helped. As I said, it's probably not the best way, but it will work.. You probably need to have a look at your associations, etc to see why user_id isn't coming in when you do build. – Abram Oct 13 '12 at 21:11