Rails : 가상 속성 및 양식 값
-
06-07-2019 - |
문제
책 양식에서 편집기를 만들기위한 가상 속성이있는 모델 북이 있습니다. 코드는 다음과 같습니다.
class Book < ActiveRecord::Base
has_many :book_under_tags
has_many :tags, :through => :book_under_tags
has_one :editorial
has_many :written_by
has_many :authors, :through => :written_by
def editorial_string
self.editorial.name unless editorial.nil?
""
end
def editorial_string=(input)
self.editorial = Editorial.find_or_create_by_name(input)
end
end
그리고 새로운 형태 :
<% form_for(@book,
:html => { :multipart => true }) do |f| %>
<%= f.error_messages %>
...
<p>
<%= f.label :editorial_string , "Editorial: " %><br />
<%= f.text_field :editorial_string, :size => 30 %> <span class="eg">Ej. Sudamericana</span>
</p>
...
이를 통해 Form Data No Validations를 통과 할 때 양식이 재생 될 때 편집 필드에 제출 된 데이터를 잃어 버렸고 새로운 편집기가 생성됩니다. 이 두 가지 문제를 어떻게 해결할 수 있습니까? 나는 루비에서 꽤 새롭고 해결책을 찾을 수 없습니다.
내 컨트롤러 업데이트 :
def create
@book = Book.new(params[:book])
respond_to do |format|
if @book.save
flash[:notice] = 'Book was successfully created.'
format.html { redirect_to(@book) }
format.xml { render :xml => @book, :status => :created, :location => @book }
else
format.html { render :action => "new" }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity }
end
end
end
해결책
나는 당신의 책#editorial_string 메소드가 항상 "" "원인이라고 생각합니다. 다음으로 단순화 할 수 있습니다.
def editorial_string
editorial ? editorial.name : ""
end
주석을 기반으로 업데이트 :
중첩 된 양식을하고 싶은 것 같습니다. (보다 API 문서에서 accept_nested_attributes_) 이것은 레일 2.3에서 새로운 것입니다.
따라서 책 수업을 업데이트하면
class Book < ActiveRecord::Base
accepts_nested_attributes_for :editorial
...
end
(이제 editorial_string =, editorial_string 메소드도 제거 할 수도 있습니다)
양식을 다음과 같은 것과 같은 것으로 업데이트하십시오
...
<% f.fields_for :editorial do |editorial_form| %>
<%= editorial_form.label :name, 'Editorial:' %>
<%= editorial_form.text_field :name %>
<% end %>
...
다른 팁
첫 번째 문제는 그 것입니다
def editorial_string
self.editorial.name unless editorial.nil?
""
end
마지막 줄이기 때문에 항상 ""가 항상 돌아옵니다.
def editorial_string
return self.editorial.name if editorial
""
end
그 문제를 해결할 것입니다. 검증이 통과하지 않는 한, 컨트롤러에서 무엇을하고 있습니까? 어떤 유효성 검사 오류가 발생합니까?
이 팟 캐스트를 살펴보십시오 http://railscasts.com/episodes/167-more-on-virtual-attributes. editorial_string = (입력) 메소드에서 find_or_create를 이동하여 저장 후 다시 호출해야한다고 생각합니다.