Bill W.
Bill W.

Reputation: 47

form_for in Ruby on Rails app

I am trying to create a school model, which users can create, with the attributes of :school_name (string) , :description (string), and :created_by_user (integer).

The users should only be able to access and change the name and description parameters, and the created_by_user field should be automatically set to the id# of the user who created it.

this is my form for a new school:

<h1>Open a New School</h1>

<%= form_for(@school) do |f| %>
 <%= render 'shared/error_messages', :object => f.object %>
<%= render 'fields', :f => f %>
<div class="actions">
<%= f.submit "Create School!" %>
</div>  

and this is the "fields" partial

<div class="field">
  <%= f.label :school_name %><br />
  <%= f.text_field :school_name %>
</div>
<div class="field">
 <%= f.label :description %><br />
 <%= f.text_area :description, :size => "45x10" %>
 </div>

What can I add in the "fields" partial, or anywhere else, so that when users create a new school their ID automatically gets set as the created_by_user value?

Thanks

Upvotes: 0

Views: 110

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

You'll want to define this in your controller, rather than your view. Something like:

class SchoolsController < ApplicationController

  def create
    @school = School.new(params[:school])
    @school.created_by_user = current_user
    if @school.save
      redirect_to @school, notice: "School Created"
    else
      render :new
    end
  end
end

Upvotes: 1

Related Questions