2012-06-18 7 views
0

:별칭을 accepts_nested_attributes_입니까? <code>Topic</code> 모델에서

class Topic < ActiveRecord::Base 
    has_many :choices, :dependent => :destroy 
    accepts_nested_attributes_for :choices 
    attr_accessible :title, :choices 
end 

게시물 동안 작성, 제출 params 대신 :choices_attributes의, 레일 예상 :choices이며, 오류 제공 :

ActiveRecord::AssociationTypeMismatch (Choice(#70365943501680) expected, 
got ActiveSupport::HashWithIndifferentAccess(#70365951899600)): 

것은 거기는 accepts_nested_attributes_for을 config (설정) 할 수있는 방법이다 JSON 호출에서 choices_attributes 대신에 choices으로 전달되는 매개 변수를 허용 하시겠습니까?

def create 
    choices = params[:topic].delete(:choices) 
    @topic = Topic.new(params[:topic]) 
    if choices 
     choices.each do |choice| 
     @topic.choices.build(choice) 
     end 
    end 
    if @topic.save 
     render json: @topic, status: :created, location: @topic 
    else 
     render json: @topic.errors, status: :unprocessable_entity 
    end 
    end 

답변

0

당신은

def choices=(params) 
    self.choices_attributes = params 
end 

하지만 '로 모델의 방법 choices=을 만들 수 있습니다

현재, 나는 (우아한 솔루션을 수 없습니다 보인다) 컨트롤러의 속성을 생성했다 너의 세터와 선택의 관계를 깨뜨릴거야.

가장 좋은 방법은 choices_attributes 대신 choices

0

이 오래된 질문이다 반환 할 양식을 수정하는 것입니다,하지만 난 그냥 같은 문제 다 퉜다. 이것 주위에 다른 방법이 있습니까? "_attributes"문자열이 nested_attributes.rb 코드 (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L337)에 하드 코드 된 것처럼 보입니다.

양식을 제출할 때 속성에 "choices_attributes"를 할당해도 문제가 없지만 API에 사용되는 경우에는 무엇이 있습니까? 이 경우 단지 이해가되지 않습니다.

JSON을 API로 전달할 때이 문제를 해결할 수있는 방법이 있습니까?

감사합니다.

UPDATE :

글쎄, 난 여기에 대한 업데이트가 내가 지금이 바로 주위지고있어 어떻게 보여 드리겠습니다 들어 있지 않기 때문에. 레일스에 익숙하지 않아서 나는 제안에 개방적이지만, 이것이 지금 내가 알아낼 수있는 유일한 방법이다.

나는이 방법은 기본적으로는 accepts_nested_attributes_for와 함께 작동하도록 # {ATTR} _attributes로 전달되는 모든 속성을 변환 내 API의 base_controller.rb

def adjust_for_nested_attributes(attrs)  
    Array(attrs).each do |param| 
    if params[param].present? 
     params["#{param}_attributes"] = params[param] 
     params.delete(param) 
    end 
    end 
end 

에 adjust_for_nested_attributes 방법을 만들었습니다.

는이 기능을 필요로 각 컨트롤러에서 나는 그렇게

before_action only: [:create] do 
    adjust_for_nested_attributes(:choices) 
end 

지금 내가 창조에 대한 유일한 걱정 같은 before_action을 추가,하지만 당신은 업데이트를 필요한 경우는 '단지에 그것을 추가 할 수 있습니다 '절을 참조하십시오.

0
# Adds support for creating choices associations via `choices=value` 
    # This is in addition to `choices_attributes=value` method provided by 
    # `accepts_nested_attributes_for :choices` 
    def choices=(value) 
    value.is_a?(Array) && value.first.is_a?(Hash) ? (self.choices_attributes = value) : super 
    end 
관련 문제