Reputation: 1426
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!
Upvotes: 0
Views: 2125
Reputation: 1
You can use hidden field tag.
View:
<%= hidden_field_tag 'user_id', current_user.id %>
Upvotes: -1
Reputation: 5403
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?
Upvotes: 2
Reputation: 77993
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.
Upvotes: 3