Rails 4에서 연결을 통해 조인 테이블 및 has_many 문제

안잔

여러분, 이것이 제 DB 구조입니다. AccountGrade.rb MODEL은 계정 및 등급 모델에 대한 조인 테이블입니다.

class AccountGrade < ActiveRecord::Base
  belongs_to :account
  belongs_to :grade
  attr_accessor :grade
  attr_accessor :section
end

내 account.rb 모델

class Account < ActiveRecord::Base
  has_many :grades, :through => :account_grades
  has_many :account_grades
  belongs_to :user
  validates :school_name,:line_1,:city,:state,:country,:pincode,:phone_number, :presence => true
  validates :pincode,:phone_number,numericality: { only_integer: true }
end

내 grade.rb 모델

class Grade < ActiveRecord::Base
  has_many :accounts, :through => :account_grades
  has_many :account_grades
  attr_accessor :account_grades
end

내 grades_controller.rb

class GradesController < ApplicationController
  def index
    @grades = Grade.all
    render json: {
      Grades:@grades
    }.to_json
  end

  def add_class_sections
    # unless params[:section]
      @account_grades = AccountGrade.new class_sections_params
      puts "Grades are #{@account_grades}"

      @grades.each do |grade|
        @account_grades = grade
        puts grade
        puts @account_grades
      end
    # end #unless ends here
  end #function add_class_sections ends here


  private

    def class_sections_params
      params.permit!
      # params.require(:gardes).permit(:section)#, :email, :password, :salt, :encrypted_password)
    end

end #class ends here

터미널 추적에서 아래 오류가 발생합니다.

Started POST "/add_classes?grade_id[0]=1&section[0]=2&grade_id[1]=2&section[1]=1&grade_id[2]=3&section[2]=1" for 127.0.0.1 at 2015-11-17 12:43:47 +0530
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by GradesController#add_class_sections as */*
  Parameters: {"grade_id"=>{"0"=>"1", "1"=>"2", "2"=>"3"}, "section"=>{"0"=>"2", "1"=>"1", "2"=>"1"}}
Completed 500 Internal Server Error in 10ms (ActiveRecord: 0.8ms)

ActiveRecord::UnknownAttributeError (unknown attribute 'controller' for AccountGrade.):
  app/controllers/grades_controller.rb:11:in `add_class_sections'


  Rendered /home/anjan/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (11.0ms)
  Rendered /home/anjan/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)
  Rendered /home/anjan/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
  Rendered /home/anjan/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (24.8ms)
리처드 펙

와우 코드에 많은 문제가 있습니다.

당신의 추론에 관계없이, 이것이 당신이 그것을 작동시키는 방법입니다 ...


#app/controllers/grades_controller.rb
class GradesController < ApplicationController
    def index
      @grades = Grade.all
      respond_to do |format|
         format.json { render json: @grades.to_json }
         format.html
      end
    end

    def create
      @account_grades = AccountGrade.new class_sections_params
      redirect_to @account.grades if @account_grades.save
    end

  private

    def sections_params
      params.require(:grades).permit(:section)
    end
end

이 코드가 작동하면 controller속성을 찾는 이유 (이상한 오류) 를 이해할 수있는 훨씬 더 강력한 위치에있게됩니다 .

또한 Rails의 몇 가지 규칙을 알고 있어야합니다.

  1. 사용하지 마십시오 puts컨트롤러에 - 당신은 Rails.logger.info()당신의 콘솔에 출력.
  2. 당신의 행동을 안정되게 유지하십시오 -비록 이것이 깨질 수 있고 종종 깨질 수 있지만, Rails 컨트롤러의 안정된 특성은 따라야 할 가장 중요한 규칙이어야합니다. 꼭 필요한 add_class_section경우가 아니면 호출 하지 마십시오. 대신 필요에 따라 new& create메서드를 사용해야합니다.

-

또한 모든 attr_accessor참조 , 특히 연관 이름과 충돌 하는 참조를 모두 제거하십시오 .

attr_accessor기본적으로 모델에 대한 새로운 getter/ setter메소드를 선언 합니다. 이러한 메서드가 관계를 재정의하면 실제로 작동하지 못하게됩니다.

attr_accessor반영구 속성 (DB에 저장하지 않는 IE 속성)을 생성하려는 경우 아니면 필요 하지 않습니다. attr_accessorRails에서 가장 일반적인 용도 가상 속성 을 만드는 것입니다 .

여기에 이미지 설명 입력

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

뷰에 조인 테이블 행 표시 (연결을 통해 has_many)

분류에서Dev

여러 범위와의 연결을 통해 has_many에서 동일한 테이블의 여러 조인을 제거하는 방법은 무엇입니까?

분류에서Dev

Rails 4에서 연관을 통해 has_many 사용

분류에서Dev

상속 문제와의 연관을 통해 Rails has_many

분류에서Dev

동일한 STI 모델을 통해 Rails 연관 has_many 및 has_many

분류에서Dev

Rails 4 has_many 조인 테이블 관리 속성 증가

분류에서Dev

조인 테이블을 통해 has_many에 부울 항목을 저장하는 방법

분류에서Dev

추가 확인란을 통해 조인 테이블 has_many 업데이트

분류에서Dev

Rails 4 : : has_many, : through 및 테이블 이름

분류에서Dev

Rails : has_many : through 연관에있는 조인 테이블의 여러 새 레코드에 속성 값 추가

분류에서Dev

Rails는 연관을 통해 has_many를 삭제합니다.

분류에서Dev

Rails 4 has_many 문제

분류에서Dev

Rails 4 has_many 문제

분류에서Dev

Rails 4 연결을 has_many / belongs_to를 사용하여 두 테이블에 자동으로 저장하려면 어떻게해야합니까?

분류에서Dev

액세스 조인 테이블 속성을 통한 has_many 양식

분류에서Dev

다음을 통해 has_many에 대한 조인 테이블 속성을 우아하게 설정하십시오.

분류에서Dev

관계를 통해 has_many의 조인 엔티티에 대한 Rails 필드

분류에서Dev

여러 유형에 대해 source 및 source_type으로 앨리어싱을 통해 Rails has_many

분류에서Dev

연결에서 조인 테이블 속성 (has_many : through)에 액세스하는 방법

분류에서Dev

where 절을 통해 has_many 및 has_many

분류에서Dev

다른 역할을 할당하면서 Rails에서 Has_many를 통해

분류에서Dev

has_many : 관계 조작을 통해

분류에서Dev

Rails ActiveRecord : has_and_belongs_to_many 관계 조인 테이블에 대한 맞춤 주문을 어떻게 제공 할 수 있습니까?

분류에서Dev

MSSQL의 테이블에서 부분 문자열을 통해 조인

분류에서Dev

rails has_many : 연결을 통해 작동하지 않습니다.

분류에서Dev

has_many, through, class_name 및 where 절이있는 Rails 모델 연결

분류에서Dev

has_many through ... 그러나 두 개의 조인 테이블 깊이에 대한 레일의 연관 처리

분류에서Dev

여러 모델에서 작동하지 않음을 통해 Rails 연관 has_many

분류에서Dev

모든 has_many의 연결이 'true'인 경우에만 상위 레코드를 선택하는 Rails 쿼리

Related 관련 기사

  1. 1

    뷰에 조인 테이블 행 표시 (연결을 통해 has_many)

  2. 2

    여러 범위와의 연결을 통해 has_many에서 동일한 테이블의 여러 조인을 제거하는 방법은 무엇입니까?

  3. 3

    Rails 4에서 연관을 통해 has_many 사용

  4. 4

    상속 문제와의 연관을 통해 Rails has_many

  5. 5

    동일한 STI 모델을 통해 Rails 연관 has_many 및 has_many

  6. 6

    Rails 4 has_many 조인 테이블 관리 속성 증가

  7. 7

    조인 테이블을 통해 has_many에 부울 항목을 저장하는 방법

  8. 8

    추가 확인란을 통해 조인 테이블 has_many 업데이트

  9. 9

    Rails 4 : : has_many, : through 및 테이블 이름

  10. 10

    Rails : has_many : through 연관에있는 조인 테이블의 여러 새 레코드에 속성 값 추가

  11. 11

    Rails는 연관을 통해 has_many를 삭제합니다.

  12. 12

    Rails 4 has_many 문제

  13. 13

    Rails 4 has_many 문제

  14. 14

    Rails 4 연결을 has_many / belongs_to를 사용하여 두 테이블에 자동으로 저장하려면 어떻게해야합니까?

  15. 15

    액세스 조인 테이블 속성을 통한 has_many 양식

  16. 16

    다음을 통해 has_many에 대한 조인 테이블 속성을 우아하게 설정하십시오.

  17. 17

    관계를 통해 has_many의 조인 엔티티에 대한 Rails 필드

  18. 18

    여러 유형에 대해 source 및 source_type으로 앨리어싱을 통해 Rails has_many

  19. 19

    연결에서 조인 테이블 속성 (has_many : through)에 액세스하는 방법

  20. 20

    where 절을 통해 has_many 및 has_many

  21. 21

    다른 역할을 할당하면서 Rails에서 Has_many를 통해

  22. 22

    has_many : 관계 조작을 통해

  23. 23

    Rails ActiveRecord : has_and_belongs_to_many 관계 조인 테이블에 대한 맞춤 주문을 어떻게 제공 할 수 있습니까?

  24. 24

    MSSQL의 테이블에서 부분 문자열을 통해 조인

  25. 25

    rails has_many : 연결을 통해 작동하지 않습니다.

  26. 26

    has_many, through, class_name 및 where 절이있는 Rails 모델 연결

  27. 27

    has_many through ... 그러나 두 개의 조인 테이블 깊이에 대한 레일의 연관 처리

  28. 28

    여러 모델에서 작동하지 않음을 통해 Rails 연관 has_many

  29. 29

    모든 has_many의 연결이 'true'인 경우에만 상위 레코드를 선택하는 Rails 쿼리

뜨겁다태그

보관