views:

178

answers:

3

Hey, need a little help here.

I have two models:

class User < ActiveRecord::Base
  has_many :jobs
end

and

class Job < ActiveRecord::Base
  belongs_to :user
end

When i do migration i put

class CreateJobs < ActiveRecord::Migration
  def self.up
    create_table :jobs do |t|
      t.references :user
.....

What should i put on my jobs/new action for user_id?

I use resfull_authentication, so i have current_user helper.

<% form_for(@job) do |f| %>
  <%= f.error_messages %>

  <p>
 User:
 <%= f.label current_user.login %> #works fine for me! current_user.id works fine two!

     ??????????????? But what should i put for value???????

  </p>


  <p>
    <%= f.label :filename %><br />
    <%= f.text_field :filename %>
  </p>

Should i put current_user.id on controller? If so, how ?

Please help! Thank you very much!

A: 

Edit after more info:

In your controller, do something like:

@user = User.find_by_id(session[:user_id])
@job = Job.new(params[:job])
@user.jobs << job

Original answer:

You could have something like:

<%= f.collection_select :user_id, User.find(:all, :order => "name ASC"),
        :id, :name, {:include_blank => true} %>

This'll give you a dropdown with user names in alphabetical order.

JRL
That's cool, thanks. An what if i want to put there exact current user ?
TJY
I guess I don't quite understand your question. What exactly are you trying to do with this form?
JRL
When i create a new Job, i want to put current user id (the id of user who creates a Job) to user_id. So that way i will know then, who create that job. I even don't need to see that on my view. That value have to puts there automatically
TJY
+1  A: 
def new
  @job = current_user.jobs.new
end

def create
  @job = current_user.jobs.build(params[:job])
  if @job.save
    redirect_to @job
  else
    render 'new'
  end
end

When the job gets created, the user_id column will automatically be assigned to the current_user id.

Is this what you're trying to do?

bensie
A: 

You can use hidden field tag.

View:

<%= hidden_field_tag 'user_id', current_user.id %>
RoRman