I have a form on a page that a user can use to create a course. While I understand how to get provide the user the opportunity to fill in simple things like the course name and description, I also want to assign the user’s id to a teacher_id column. This should be done automatically for the user and they shouldn’t see an opportunity to assign a teacher_id as it should be their id.
Currently the “Create a course” page’s view is this:
<% provide(:title, 'My Classes') %>
<h1>Create a class!</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@course) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description, :size => "30x6" %>
<!-- Assign the current user's id to the teacher_id column in the background -->
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
And the new action in the course controller looks like:
def new
@course = Course.new
end
What’s the best way to accomplish what I want to do? I’m pretty new to Rails and I haven’t had much experience with forms and all the possibilities. I read a little bit on the hidden_field_tag but I don’t know if that’s the kind of thing I need and I was finding it difficult to get the user’s id in the form anyway. Do I need to make a user instance variable in the controller or can I do it with code in the view somehow.
Thanks for the help.
You can use the hidden_field:
EDIT – to explain how to have the
current_useravailable in the form.I normally have a
sessioncontroller that is responsible for login and logout users, creating asessionto keep the user logged in.The create action for example:
If the combination of username and password are correct, it will create a
sessionwith theuser_id(session[:user_id]).Now, in your
application_controlleryou can have something like the below:The
helper_methodallows you to use thecurrent_userin any controller or view in your application.I hope it helps….