简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM