1

私はそのモデルのDeveloperモデルを持ってい:has_one Userます。これにより、さまざまなユーザー タイプ間での認証などを行うことができます。

正しくないユーザー データで新しい Developer を作成すると、検証エラーのリストが表示されます。開発者を誤ったユーザー データで更新すると、編集フォームが再レンダリングされるだけで (必要に応じて)、検証エラーは表示されません。

私の検証エラー表示コードは、フォームの部分的なフィールドにあるため、違いはありません。

モデルを更新しようとしている方法に問題があるように感じます。

def update
  @developer = Developer.find(params[:id])
  if @developer.user.update_attributes(params[:user]) && @developer.update_attributes(params[:developer])
    flash[:success] = "Profile Updated"
    sign_in @developer.user
    redirect_to @developer
  else
    render 'edit'
  end
end

そして私のUser検証は空想的なものではありません:

validates :name,  presence: true, length: {maximum: 30}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, 
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
validates :password, length: {minimum: 6}
validates :password_confirmation, presence: true

私は少なくとも 10 の異なる同様の投稿を読みましたが、助けになるものは何も見つかりませんでした。どんな助けでも素晴らしいでしょう。

編集

updateフォームを送信すると、次のパラメーターが送信されます

Parameters: {"utf8"=>"✓", "authenticity_token"=>"70xmNVxxES7lK2bSIIul/i5GaiJhB9+B5bV/bUVFlTs=", "user"=>{"name"=>"foo", "email"=>"foo@example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "developer"=>{"skype_name"=>""}, "commit"=>"Save changes", "id"=>"11"}

Userそれはまだ検証を行いません。コンソール経由で次の操作を行うと、動作します (つまり、パラメーターが適切な場合は保存され、パラメーターが不適切な場合は失敗します)。

Developer.last.update_attributes(:user_attributes => {:name => "test updated", :email => "test@example.com", :password => "123456", :password_confirmation => "123456"})

ですから、私と違うように見える唯一のことは、私のフォームが私に与えていること:user_attributesだけではありません. :userどうすればそれを変更できますか?

編集 2

フォームの私のパーシャルの関連部分_fields:

<%= render 'shared/error_messages' %>

<%= fields_for :user do |user| %>
  <%= user.label :name %>
  <%= user.text_field :name %>

  <%= user.label :email %>
  <%= user.text_field :email %>

  <%= user.label :password %>
  <%= user.password_field :password %>

  <%= user.label :password_confirmation, "Confirm Password" %>
  <%= user.password_field :password_confirmation %>
<% end %>

そして私のDeveloper#edit行動:

def edit
  @developer = Developer.find(params[:id])
end
4

1 に答える 1

1

ユーザーと開発者を別々に保存する必要はありません。このような開発者モデルを介してユーザーを保存することができます。

    <%= form_for(@developer) do |f| %>

      ... developer's attribute ...

           <%= f.fields_for :user do |ff| %>
            ... user's attribute ...

コントローラーのみ

   @developer = Developer.find(params[:id])
   if @developer.update_attributes(params[:developer])
       ....

開発者モデルでは、追加するだけで済みます。

     accepts_nested_attributes_for :user

     attr_accessible :user_attribute

form_for は、ユーザーのモデルの検証エラーも自動的に表示するようになりました。

詳細については、このリンクを参照してくださいhttp://rubysource.com/complex-rails-forms-with-nested-attributes/

于 2013-04-22T07:20:16.007 に答える