I’m searching a solution to have a pre-validation for a nested resource before the submition of an entire form in rails and don’t have a clue on the correct design.
So I have a simple User model that has_one :place being accepted for nested attributes:
class User < ActiveRecord::Base
...
has_one :place, :dependent => :destroy
accepts_nested_attributes_for :place
attr_accessible :place_attributes
...
end
The Place model contains attributes such as :street_number, :street, :postal_code, :city, :country.
I’d like to setup a form for the edit of user so that he can introduce the place. Before submit, I’d like to give the user the opportunity to validate the place. So I set up a custom action in the PlaceController.
# place_controller.rb
class PlaceController < ApplicationController
...
def validate
# code for validation
end
end
By the way I defined the routes for the place as follow:
# route.rb
resources :users do
resource :place do
match 'validate', :to => 'place#validate'
end
end
Then in the view I set up the form:
<%= form_for(:user, :url => edit_user_path(@user), :html => {:method => :put, :multipart => true}) do |f| %>
<%= f.text_field :name %>
# other fields for users
...
<%= f.fields_for :place do |builder| %>
<%= render 'places/form', :f => builder %>
<% end %>
<%= f.submit "Update" %>
And the partial places/form manages the fields for the nested attributes of place:
<%= f.text_field :street_number %>
<%= f.text_field :street %>
...
Here is the point: I’d like to have a submit or link to call the validate action with the attributes of the place model.
I tried something like:
<%= link_to 'Validate', validate_user_place_path(@user, :format => :js, :params_to_validate => f.object), :remote => true %>
Even if it calls correctly the controller, I don’t get the attributes to be validated in the controller.
What shall I do?
Thanks for your help!
To my-self:
I finally made it by adding two simple buttons in the form with a name to one of the button in order to identify the action taken. I just followed the idea behind the following railscast: Railscast 38 .
So in the view:
And in the
Usercontroller, I check for the button in theupdateaction:The only missing point is that it is not ajax base. What a pitty!
Cheers…
I’m a poor lonesome cowboy…