2014-09-02 2 views
0

두 모델 간의 연결은 belongs_tohas_many입니다. 나는 사용자 생성 과정을 통해 사용자를 생성하고 조직을 생성하고 둘을 연관시키는 사용자 생성 양식을 가지고있다. 조직 이름의 존재를 확인했습니다. 해당 유효성 검사가 실패하면 User과 같은 오류 메시지와 동일한 해시에 Name cannot be blank 오류를 추가하려고합니다 (Organiation). 기본적으로 오류 메시지 목록을 하나 만듭니다.레일 4 - 중첩 된 연결에 대한 오류 표시

다음
class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable 

    belongs_to :organization 

    validates_presence_of :display_name 
end 

class Organization < ActiveRecord::Base 
    has_many :users, dependent: :destroy 

    accepts_nested_attributes_for :users, :allow_destroy => true 

    validates_presence_of :name 
end 

내 생성의 Action :

: 여기
def create 
    @user = User.new(sign_up_params) 
    if params[:user][:organization][:access_code].blank? 
    # create new organization 
    @access_code = "#{SecureRandom.urlsafe_base64(16)}#{Time.now.to_i}" 
    @organization = Organization.create(name: params[:user][:organization][:name], access_code: @access_code) 
    @user.organization_id = @organization.id 
    @user.is_admin = true 
    else 
    # try and add someone to an organization 
    @organization = Organization.find(:all, conditions: ["name = ? AND access_code = ?", params[:user][:organization][:name], params[:user][:organization][:access_code]]) 
    if @organization.empty? 
     flash.now[:error] = "No organization has been found with that name and access code." 
     render :new 
     return 
    else 
     @user.organization_id = @organization.first.id 
    end 
    end 
    if @user.save 
    flash[:success] = "Your account has been successfully created! Check your email for a confirmation link to activate your account." 
    redirect_to sign_in_path 
    else 
    flash.now[:error] = "Something went wrong! Please try again." 
    render :new 
    end 
end 

내 뷰의 다음 error_messages 부분

<% provide(:title, 'Sign Up') %> 

<h1>Create Account</h1> 

<%= nested_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 
    <%= render "shared/error_messages", obj: @user %> 

    <fieldset> 
    <legend>Account Information</legend> 
    <div class="form-group"> 
     <%= f.label :email %> 
     <%= f.email_field :email, class: "form-control", autofocus: true %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :display_name, "Display Name" %> 
     <%= f.text_field :display_name, class: "form-control" %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %> 
     <%= f.password_field :password, class: "form-control", autocomplete: "off" %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password_confirmation %> 
     <%= f.password_field :password_confirmation, class: "form-control", autocomplete: "off" %> 
    </div> 
    </fieldset> 
    <%= f.fields_for :organization do |o| %> 
    <fieldset> 
     <legend>Organization Information</legend> 
     <p> 
     <strong>Creating a New Organization:</strong> Fill out the Organization Name field, but leave the Access Code field blank.<br /> 
     <strong>Joining an Existing Organization:</strong> Fill out both the Organization Name and Access Code field, using the access code that you received from someone at your organization. 
     </p> 
     <div class="form-group"> 
     <%= o.label :name, "Organization Name" %> 
     <%= o.text_field :name, class: "form-control" %> 
     </div> 
     <div class="form-group"> 
     <%= o.label :access_code, "Organization Access Code" %> 
     <%= o.text_field :access_code, class: "form-control" %> 
     </div> 
    </fieldset> 
    <% end %> 
    <div class="form-actions"> 
    <%= f.submit "Create Account", class: "btn btn-primary" %> 
    <%= link_to "Cancel", :back %> 
    </div> 
<% end %> 

<%= render "users/shared/links" %> 

그리고, 여기 여기

내 모델입니다3210

User과 같이 표시되는 오류는 Organization이 아니므로 표시됩니다. 부분적으로 @user을 전달하는 것과 관련이있을 수 있습니까?

+0

사용자에게만 전달되는 경우 사용자 개체에 대한 오류 메시지 만 표시된다는 것이 맞습니까? 귀하의 컨트롤러에서 flash.now [: error] = "..."라고 말하는 대신 flash.now [: errors] = @ user.errors.full_messages + @ organization.errors와 같은 말을 해보시겠습니까? full_messages? – stefvhuynh

+0

플래시 메시지는 실제로이 문제와 관련이 없습니다. 문제는 내가 믿는 모델을 통해 설정 한 ActiveModel 유효성 검사입니다. 나는'@ user'를 전달하는 것이 좋을 것이고 조직 오류는'@ user.organization'을 통해 들어올 것이라고 가정하고 있습니다. – ryanpitts1

답변

0

좋아, 내가 내 문제를 알아낼. 모델 연관을 가지고 뒤로 물러나거나 적어도 accepts_nested_attributes과 같은 것들이있을 것 같습니다.

다음
class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :timeoutable 

    belongs_to :organization 

    accepts_nested_attributes_for :organization 

    validates_presence_of :display_name 
end 

class Organization < ActiveRecord::Base 
    has_many :users, dependent: :destroy 

    validates_presence_of :name 
end 

내 컨트롤러 동작을 만들 업데이트 내된다 : 여기

def create 
    @user = User.new(sign_up_params) 
    if params[:user][:organization_attributes][:access_code].blank? 
    # create new organization 
    @access_code = "#{SecureRandom.urlsafe_base64(16)}#{Time.now.to_i}" 
    @organization = Organization.create(name: params[:user][:organization_attributes][:name], access_code: @access_code) 
    @user.organization_id = @organization.id 
    @user.is_admin = true 
    else 
    # try and add someone to an organization 
    @organization = Organization.find(:all, conditions: ["name = ? AND access_code = ?", params[:user][:organization_attributes][:name], params[:user][:organization_attributes][:access_code]]) 
    if @organization.empty? 
     flash.now[:error] = "No organization has been found with that name and access code." 
     render :new 
     return 
    else 
     @user.organization_id = @organization.first.id 
    end 
    end 
    if @user.save 
    flash[:success] = "Your account has been successfully created! Check your email for a confirmation link to activate your account." 
    redirect_to sign_in_path 
    else 
    flash.now[:error] = "Something went wrong! Please try again." 
    render :new 
    end 
end 

내 업데이트보기 : 여기

<% provide(:title, 'Sign Up') %> 

<h1>Create Account</h1> 

<%= nested_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 
    <%= render "shared/error_messages", obj: @user %> 

    <fieldset> 
    <legend>Account Information</legend> 
    <div class="form-group"> 
     <%= f.label :email %> 
     <%= f.email_field :email, class: "form-control", autofocus: true %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :display_name, "Display Name" %> 
     <%= f.text_field :display_name, class: "form-control" %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %> 
     <%= f.password_field :password, class: "form-control", autocomplete: "off" %> 
    </div> 
    <div class="form-group"> 
     <%= f.label :password_confirmation %> 
     <%= f.password_field :password_confirmation, class: "form-control", autocomplete: "off" %> 
    </div> 
    </fieldset> 
    <% @user.build_organization unless @user.organization %> 
    <%= f.fields_for :organization do |o| %> 
    <fieldset> 
     <legend>Organization Information</legend> 
     <p> 
     <strong>Creating a New Organization:</strong> Fill out the Organization Name field, but leave the Access Code field blank.<br /> 
     <strong>Joining an Existing Organization:</strong> Fill out both the Organization Name and Access Code field, using the access code that you received from someone at your organization. 
     </p> 
     <div class="form-group"> 
     <%= o.label :name, "Organization Name" %> 
     <%= o.text_field :name, class: "form-control" %> 
     </div> 
     <div class="form-group"> 
     <%= o.label :access_code, "Organization Access Code" %> 
     <%= o.text_field :access_code, class: "form-control" %> 
     </div> 
    </fieldset> 
    <% end %> 
    <div class="form-actions"> 
    <%= f.submit "Create Account", class: "btn btn-primary" %> 
    <%= link_to "Cancel", :back %> 
    </div> 
<% end %> 

<%= render "users/shared/links" %> 

내입니다 여기에

내 업데이트 된 모델입니다 error_messages 부분을 업데이트했습니다 (컨텍스트에 대해 표시 - 변경된 코드는 실제로 문제와 관련이 없습니다) :

이제 정보를 입력하지 않고 저장하려고하면 모든 올바른 오류가 표시됩니다. 또한 필요한 모든 사용자 데이터를 입력하고 모든 조직 필드를 비워두면 올바른 조직 관련 유효성 검사 오류가 표시되고 사용자 레코드가 만들어지지 않습니다. 내가 지금 필요로하는 것처럼 작동한다.