2017-05-07 9 views
1

Ruby on Rails를 배우고 있는데이 문제가 있습니다. 나는 다른 유사한 문제를 보았지만 나에게 도움이되는 해결책을 찾지 못했다.NoMethodError in Books #

모든 것이 올바르게 작동했지만 사용자가 이미지를 선택할 수 있도록 f.file_field을 추가했습니다. 이제 사용자가 이미지를 선택하면이 오류가 발생하지만 오류가 발생하지 않는다면 오류가 발생합니다.

enter image description here

이이 오류를

def new 
    @book = current_user.books.build 
    @categories = Category.all.map{ |c| [c.name, c.id] } 
    end 

    def create 
    @book = current_user.books.build(book_params) 
    @book.category_id = params[:category_id] 

    if @book.save 
     redirect_to root_path 
    else 
     render 'new' 
    end 
    end 

를 일으키는 내가 생각하는 컨트롤러의 일부 도서

class Book < ApplicationRecord 
    belongs_to :user 
    belongs_to :category 

    has_attached_file :book_img, styles: { book_index: "250x350>", book_show: "325x475>" }, default_url: "/images/:style/missing.png" 
    validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/ 

end 

내 모델입니다 그리고 이것은 뷰

이다
<%= simple_form_for @book, :html => { :multipart => true } do |f| %> 
    <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a category") %> 
    <%= f.file_field :book_img %> 
    <%= f.input :title, label: "Book Title" %> 
    <%= f.input :description %> 
    <%= f.input :author %> 
    <%= f.button :submit %> 

<% end %> 

사용자가 도서 카테고리를 선택할 수있는 select_tag에 오류가 표시되는 이유를 모르겠습니다.

루비 : 루비 2.2.6p396

레일 : 당신은 create 액션 내부 @categories 변수를 설정해야합니다 5.0.2

+0

서버를 재시작하고 다시 시도하십시오. 또한'categories' 테이블에 레코드가 있습니까? – amrrbakry

+0

서버를 여러 번 다시 시작했습니다. 그리고 나는 수동으로 카테고리를 추가했고 각 책에는 category_id가 있습니다. – CNuts

+0

'strong params'에'book_img'가 있습니까? –

답변

1

레일. create 조치가이 @categories 변수 안에 가능한 범주로 선택 태그를 채우기 위해 시도 new 템플릿을 렌더링 실패 할 경우

def create 
    @book = current_user.books.build(book_params) 
    @book.category_id = params[:category_id] 

    if @book.save 
    redirect_to root_path 
    else 
    @categories = Category.all.map{ |c| [c.name, c.id] } 
    render 'new' 
    end 
end 

아래로 업데이트합니다. 이 변수는 동작이 new 인 경우에만 설정되었습니다.

+0

답변 해 주셔서 감사합니다. 그게 오류를 해결했는데 왜 새 책을 만들지 않는지 아십니까? – CNuts

+0

'book_img'의 유효성 검사 때문에 가능할 가능성이 큽니다. 저장 실패 후'@ book.errors'를 검사하십시오. 그것은 무엇이 문제인지 말해야합니다. –

+0

예 클립 클립 보석에 오류가 발생했습니다. 올바르게 설치하지 않은 것 같습니다. 도와 줘서 고마워. – CNuts