Railscast에 이어 자동 완성 연결을 설정하고 있습니다.유효성 검사 오류와 양식 리디렉션에서 가상 속성을 유지하는 방법은 무엇입니까?
다른 논리를 통해 값을 전달해야하므로 virtual category_name 속성에 find_or_create
대신 find_or_initialize
을 사용하고 있습니다.
상위 모델 유효성 검사가 실패한 경우 (railscast의 제품)이 가상 속성을 유지하는 가장 좋은 방법은 무엇입니까? 오류가있는 경우 저장 경로가 양식을 렌더링 한 후 사용자가 입력 한 category_name
을 입력하고 싶습니다.
값이 params[:category_name]
을 통해 액세스 할 수 있다고 생각했지만 다시 필드로 설정할 수 없습니다.
아이디어에 감사드립니다.
편집
컨트롤러
class ProductsController < ApplicationController
...
def create
@product = current_user.products.build(params[:prerep])
if @products.save
DO SOME STUFF...
respond_to do |format|
format.html { redirect_to(@product, :notice => 'Product was successfully created.') }
format.xml { render :xml => @product, :status => :created, :location => @product }
end
else
respond_to do |format|
format.html { render :action => "new" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
end
end
모델 :
class Prerep < ActiveRecord::Base
attr_accessible ..., :category_name, ...
attr_reader ...
attr_accessor ...
belongs_to :user, :category
has_many ...
validates ...
def category_name
category.try(:name)
end
def category_name=(name)
product_category = Category.find_or_initialize_by_name(name) if name.present?
self.category = if product_category.new_record?
product_category ...SET SOME ATTRIBUTES...
product_category.save(:validate => false)
product_category
else
product_category
end
end
end
문제는 리디렉션입니다. 왜 대신 렌더링 할 수 없습니까? – apneadiving
안녕하세요, @ 가난하게 말한 질문에 사과드립니다. 컨트롤러는 실제로 리다이렉션하지 않고 eror에 양식을 렌더링합니다. 이를 반영하기 위해 질문을 업데이트했습니다. –
동일한 문제가 있습니다. 그것을 해결 했습니까? – Raoot