I have an User model who has_one :preference, but I would like to join the form to update the user and the form to update his preference, so in the user’s form, I added :
<% if !@user.new_record? %>
<div class="field">
<%= label_tag 'user_preference_quote_type', 'Type de citations' %><br />
<%= text_field_tag 'user_preference_quote_type', @user.preference.quote_type %>
</div>
<div class="field">
<%= label_tag 'user_preference_locale', 'Langage' %><br />
<%= text_field_tag 'user_preference_locale', @user.preference.locale %>
</div>
<% end %>
And in my controller :
def update
@user = User.find(params[:id])
@user.preference.quote_type = params[:user_preference_quote_type]
@user.preference.locale = params[:user_preference_locale]
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to(@user, :notice => t('c.users.update')) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
But the preferences would not change, how can I do it ? And is there is better way to do it ?
This is not a good way of doing that. You should use fields_for. It will make your form cleaner. By the way, what you’re doing in the controller is not working because you use
update_attributesto update your model that makes your assigments useless. Using the above mentionedfields_forwill help you to clean the controller too. But be careful because you surely will need accepts_nested_attributes_for in your model.