Question

I'm new to Rails, so I have a newbie question.

We have a form that lets administrators set up a new user that looks like this:

<%= form_for :user, :url => url_for(:action => 'create_user', :account_id => @account.id, :hide_form => 1), :html => {:name => 'new_user_form', :id => 'new_user_form', :remote => true} do |f| %>
  First Name:
  <% f.text_field 'first_name' %><br/>
  Last Name:
  <%= f.text_field 'last_name' %><br/>
  Username:
  <%= f.text_field 'login' %><br/>
  Email:
  <%= f.text_field 'email' %><br/>
  Agency Code:
  <%= text_field_tag 'agency_code', @default_agency_code %><br/>

  <div class="button-bar">
    <%= f.submit :id => "submit_button" %>
  </div>
<% end %>

So far, so good. The action that is called when the form is submitted shoves all of the form values into a User object and saves it to the database:

def remote_create_user
  @user = User.new(params[:user])
  @user.agency = Agency.find{|agency| agency.product_code == params[:agency_code]}
  if @user.valid? and @user.save
    # Move some stuff around for the new user
  else
    @error = "Failure to Save:"
    @user.errors.full_messages.each {|msg| @error += " - #{msg}"}
  end
end

My understanding is that the line in the view that starts <%= form_for :user lets the ERB view know to validate all of the form fields that correspond directly to the User class using the validation logic specified in the User model.

However, the last field in the form (Agency Code: <%= text_field_tag 'agency_code', @default_agency_code %><br/>) doesn't correspond with an attribute in the User model. Instead, it corresponds with Agency.product_code. The Agency model defines validation for this attribute. How can I tell Rails to use the validation logic in the Agency model for this field? If there isn't a way to do that directly, how can I add validation directly to the agency code text field?

Was it helpful?

Solution

You can simply use

@user.agency = Agency.find_by_id{|agency| agency.product_code == params[:agency_code]}

and in your user model,

validates :agency_id, :presence => true

The find_by_id will work better in this case than simply find because it returns nil if the model is not found.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top