2015-01-02 3 views
0

프로젝트의 레일즈 루비에서 튜토리얼 앱을 빌드하고 두 모델 간의 연관성을 만들려고합니다.레일 연결은 비워 둘 수 없습니다.

내 데이터베이스에는 사용자의 전자 메일 및 이벤트의 코드와 관련된 사용자, 이벤트 및 참석 테이블이 있습니다.

나는 이것을 스스로하는 법을 연구하려고 노력했지만, 사용자에게 참석 이메일의 유효성을 검사 할 때마다 새로운 것을 만들려는 것처럼 비어있을 수 없다고 명시되어 있습니다.

아직 Ruby on Rails에 새로운 것이므로 어떤 조언도 부탁드립니다! 모델은 다음과 같습니다.

사용자 모델 :

class User < ActiveRecord::Base 
    attr_accessible :email, :name, :password, :password_confirmation 
    has_secure_password 

    has_many :attendances, inverse_of: :user 
    accepts_nested_attributes_for :attendances 

    before_save { |user| user.email = email.downcase } 
    before_save :create_remember_token 

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

    private 
     def create_remember_token 
     self.remember_token = SecureRandom.urlsafe_base64 
    end 
end 

출석 모델 : 지금까지

class Attendance < ActiveRecord::Base 
    attr_accessible :code, :email 
    belongs_to :user 
    validates_presence_of :user 
end 

난 단지 사용자 및 출석 사이의 연결을 강화하기 위해 노력하고있어, 나는 일 나는 것을 일단 이벤트에 대해서도 마찬가지입니다. 또한 Rails 3.2.19와 Ruby 1.9.3입니다.

편집 : 여기 양식에 사용하는 코드가 있는데, 모델에 유효성 검사를 넣을 때까지 출석 표에 행을 작성하기 때 문에 작동한다고 생각합니다.

<% provide(:title, 'Test Event') %> 
<h1>Attendance Registration</h1> 

<div class="row"> 
    <div class="span6 offset3"> 
     <%= form_for(@attendance) do |f| %> 
     <%= render 'shared/attendance_error_messages' %> 

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

     <%= f.label :code %> 
     <%= f.text_field :code %> 

     <%= f.submit "Submit", class: "btn btn-large btn-primary" %> 
     <% end %> 
    </div> 
</div> 

또한 출석 컨트롤러가 도움이된다면 여기에 나와 있습니다.

class AttendancesController < ApplicationController 
    def new 
    @attendance = Attendance.new 
    end 

    def create 
    @attendance = Attendance.new(params[:attendance]) 
    if @attendance.save 
     flash[:success] = "Attendance logged." 
     redirect_to root_path 
    else 
     render 'new' 
    end 
    end 
end 
+0

당신이 더에 말해 주시겠습니까 사용자 존재의 오류를 방지하기 위해 양식이 줄을 추가? –

+0

나는 누군가가 이메일과 코드를 입력하여 지정된 참석자 테이블에 새로운 행을 만들 수있는 페이지를 만들었다. 그러나 그렇게 할 때 "* 사용자는 비워 둘 수 없습니다."라는 플래시 오류가 발생합니다. 또한이 페이지는 새로운 출석 행을 만드는 데 사용된다는 사실을 알고 있습니다. 출석 모델에서 유효성 검사를 입력하기 전까지 행을 올바르게 작성했기 때문입니다. – Flyte27

+0

당신이 정의한 사용자 모델에서 inverse_of와 has_may 관계를 정의하고, 참석 모델에서 inverse_of도 지정하려고합니다. belongs_to : user, : inverse_of : attendence –

답변

0

는이 오류를 얻을 때

<%= f.hidden_field :user_id, current_user.id %> 
+0

그 줄을 추가 한 후에도 여전히 사용자가 비어있는 것과 같은 문제가있는 것 같습니다. – Flyte27

+0

@RSB, 그런 종류의 접근 방식이 효과가 있지만 허점이 있습니다. 내 응답을 확인하십시오. – Humza

관련 문제