2010-12-27 8 views
5

설명되지 않은 ActiveRecord :: Relation, 정의되지 않은 메서드 오류가 발생했습니다. 이유는 모르겠지만 내 모델 연관성이 잘 정의되어 있고 이벤트 테이블에 사용자 테이블에 대한 외래 키가 있습니다. 나는이 수정 프로그램을 사용하여 시도하지만 실패 : Rails 3 ActiveRecord::Relation random associations behaviorrails 3.0.3 - ActiveRecord :: 관계, 정의되지 않은 메서드 오류

event.rb

class Event < ActiveRecord::Base 
    belongs_to :user 

    attr_accessible :event_name, :Starts_at, :finish, :tracks 
end 

user.rb

class User < ActiveRecord::Base 
    has_many :events, :dependent => :destroy 

    attr_accessible :name, :event_attributes 

    accepts_nested_attributes_for :events, :allow_destroy => true 

end 

schema.rb

ActiveRecord::Schema.define(:version => 20101201180355) do 

    create_table "events", :force => true do |t| 

    t.string "event_name" 
    t.string "tracks" 
    t.datetime "starts_at" 
    t.datetime "finish" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "user_id" 
    end 
end 

오류 메시지

NoMethodError in Users#index 
undefined method `events' for #<ActiveRecord::Relation:0x4177518> 

Extracted source (around line #10): 

7: <th><%= sortable "Tracks" %></th> 

8: </tr> 


10: <% @users.events.each do |event| %> 

11: <% debugger %> 

12: <tr> 

13:  <td><%= event.starts_at %></td> 

Trace of template inclusion: app/views/users/index.html.erb 

Rails.root: C:/rails_project1/events_manager 
Application Trace | Framework Trace | Full Trace 

app/views/users/_event_user.html.erb:10:in `_app_views_users__event_user_html_erb__412443848_34308540_1390678' 
app/views/users/index.html.erb:7:in `_app_views_users_index_html_erb___603337143_34316016_0' 
+0

@matchu 편집 해 주셔서 감사합니다. – brg

답변

5

하나user은 다수 events입니다. 귀하의 코드에서 @usersevents에 액세스하려는 것 같습니다. 아마도 명이 될 것입니다.

@users.each do |user| 
    user.events.each do |event| 
    ... 
    end 
end 

나 : 데이터베이스의 열있는 모든 속성에 대한 attr_accessible을 지정

@user.map(&:events).flatten.each do |event| 
    ... 
end 

이 또한 필요하지 않은

당신은 아마 뭔가를하고 싶어.

+0

대단히 고마워, 나는 첫 번째 옵션으로 갔고 그게 나를 위해 고정. – brg

8

오류 메시지를 자세히 읽으면 문제가 이벤트와의 관계라는 것을 나타내지 않습니다.

10

정의되지 않은 메서드`이벤트 ': <%의 @의 users.events.each가 할 | 이벤트 | 이 말한다 %>

내가 먼저

에 충돌 할 때 나는 또한 문제가이 문제를 이해했다이 @users의 파인더 대신 사용자 목록의 관계 객체 (또는 잘 명명되지 객체를 반환하는 것을 의미한다) 당신이 예상했다.

어디에서나 find를 사용하는 경우 "where (: id => ...)"로 변경해야합니다.

@users = User.where(<conditions go here>).all 

아니면 후 결과와 관련 개체를 사용할 수 있습니다 : 이것은 변경해야합니다

@users = User.find(<conditions go here>) 

: 첫 번째는 "예를 들어

, 당신은 아마 당신의 컨트롤러에서 다음과 같습니다 뭔가를 추가 조건 및 SQL "구성"에 대한 "위치"

@users = User.where(:admin => true).where('created_at > ?', min_date).order('created_at').limit(10).all 

elation 객체는 ".first".all ".each"또는 ".inspect"가 호출 될 때만 쿼리를 실행합니다.

관련 문제