#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2004
    Posts
    152
    Rep Power
    40

    Object initialization question in Rails


    I'm new with rails so I'm probably missing something easy here.

    I used scaffolding to create a "team" model and controller. I have many fileds in each team, but when I create one, I want to be able to just set the "name" field and initialize everything else to '0'.

    This is the new.html.erb file. I cut out all of the other text fields except for 'name':

    Code:
    <h1>New team</h1>
    
    <% form_for(@team) do |f| %>
      <%= f.error_messages %>
    
      <p>
        <%= f.label :name %><br />
        <%= f.text_field :name %>
      </p>
      
      <p>
        <%= f.submit "Create" %>
      </p>
    <% end %>
    
    <%= link_to 'Back', teams_path %>
    This is the 'create' function in the teams controller. Questions are in comments:
    Code:
    def create
    
        # What actually is the 'params[:team]' parameter and where is it coming from?
    # I guess I want a way to pass just the 'name' to the Team constructor (overriden?) and then initialize every other field to '0'.
        @team = Team.new(params[:team])
    
        respond_to do |format|
          if @team.save
            flash[:notice] = 'Team was successfully created.'
            format.html { redirect_to(@team) }
            format.xml  { render :xml => @team, :status => :created, :location => @team }
          else
            format.html { render :action => "new" }
            format.xml  { render :xml => @team.errors, :status => :unprocessable_entity }
          end
        end
      end
    Also, an unrelated question, what is the respond_to function and where can I read more about it?

    Thanks for any help!
    Last edited by MRAB54; September 20th, 2008 at 06:45 PM.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2001
    Location
    UK
    Posts
    77
    Rep Power
    14
    Hi,

    You can do this easily without using ruby, or rails, just set the default values in your database to 0 and then don't pass in a value for anything else. If you need to do anything more complex you should do it in the team model (skinny controllers, fat models).

    If you need to find rails documentation head over to http://api.rubyonrails.com and ruby documentation is at http://www.ruby-lang.org/en/documentation

    hth
    Jamie
    Quality UK web hosting by Media72 Hosting Limited

IMN logo majestic logo threadwatch logo seochat tools logo