레일

2010-06-11 4 views
1

임 레일의 연결에 문제가 :레일

은 현재 내가 포스트 및 사용자 모델을 가지고 있고, 관계가 이런 식으로 설정됩니다 내 애플 리케이션에,

class User < ActiveRecord::Base 
    attr_accessible :username, :name, :lastname 
    has_many :posts 
end 

class Post < ActiveRecord::Base 
    attr_accessible :title, :body 
    belongs_to :user 
end 

그러나

: 이것은 내이다

undefined method `name' for nil:NilClass 

: 임 내가이 오류가 게시물에 대한 사용자 이름에 액세스하려고 할 때 /views/posts/index.html.haml posts 테이블 user_id라는 이름의 열이있는 경우 임 잘못 appretiated 될 것입니다 무엇을의 6,

- title "Posts" 

%table 
    %tr 
    %th Title 
    %th Body 
    %th Author 
    - for post in @posts 
    %tr 
    %td= h post.title 
    %td= h post.body 
    %td= h post.user.name 
    %td= link_to 'Show', post 
    %td= link_to 'Edit', edit_post_path(post) 
    %td= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete 

%p= link_to "New Post", new_post_path 

어떤 생각이 모두의

+0

나는 행동 부분에있는 코드를 보여줄 것이다. –

+1

사용자 집합이없는'@ posts'에 하나 이상의 (또는 그 이상)'Post' 모델이있는 것처럼 보입니다. –

+0

@piemersons 컨트롤러? def show @ post = find (params [: id]) end –

답변

2

먼저 확인

그렇지 않은 경우 (당신은 DB/schema.rb에서이 테이블을 조회 할 수 있습니다) 데이터베이스 및 schema.rb에 대한 변경 사항을
$ ruby script/generate migration AddUserIdToPosts

class AddUserIdToPosts < ActiveRecord::Migration 
    def self.up 
    add_column :posts, :user_id, :integer 
    end 

    def self.down 
    remove_column :posts, :user_id 
    end 
end 

그리고 적용, 당신은 아마 마이그레이션을 작성해야 당신이 실제 User데이터 Post데이터 연관되지 않은 것처럼 $ rake db:migrate

+0

안녕하세요 앤드류, 내가 추가 했으므로 user_id 열이 없었습니다. 그러나 다음과 같은 오류가 계속 발생합니다 : 정의되지 않은 메서드 nilClass : NilClass –

+0

감사합니다. Andrew, 다음과 같이 사용자를 저널과 함께 저장하여 해결했습니다. @post = Post.new (params [ : post]) @ post.user = User.find (2) if @ post.save 플래시 [: notice] = "게시물을 만들었습니다." 렌더링 다른 @post redirect_to : 행동 => '새' 끝 이제 임 많은, 현재 기록 된 사용자에게 감사를 User.find을 변경! –

1

귀하의 의견을 바탕으로, 그것은 보인다. 당신은 연관을 설정했고 앤드류의 답변을받은 후에는 데이터베이스 스키마가 설정되어있는 것처럼 보입니다. 그러나 데이터를 어디에도 저장하지 않습니다.

는 이렇게 같은 것을 할 수 있도록 만드는 방법을 업데이트하려면 :

def PostsController < ActionController::Base 
    def create 
    # Assumes @user is already set to whatever user should be associated with the post 
    post = @user.posts.build(params[:post]) # Where params[:post] are the post inputs from your form 
    # ... 
    if post.save 
     flash[:notice] = "Successfully created post." 
     redirect_to post 
    else 
     render :action => 'new' 
    end 
    end 
end 

@user.posts.build이 (메모리) 새 게시물을 작성하고 @user 사용자 모델에 연결하는 레일을 알려줍니다. 이 표현의 등가 (그러나 더 긴) 방법은 다음과 같습니다

post = Post.new(post[:params]) 
post.user = @user 

당신이 협회와 함께 무엇을 할 수 있는지에 대한 자세한 내용은 ActiveRecord::Associations::ClassMethods 설명서를 참조하십시오.