2010-01-22 3 views
1

개체를 인스턴스화 할 때 동일한 사용자 ID를 가진 다른 개체를 생성하는 모델이 있습니다.바이 패스 attr_accessible/rail in protected

class Foo > ActiveRecord::Base 

after_create: create_bar 

private 

def create_bar 
    Bar.create(:user_id => user_id #and other attributes) 
end 

end 

Bar.rb에서 해커로부터 보호하기 위해 attr_protected가 있습니다.

class Bar > ActiveRecord::Base 
    attr_protected :user_id, :created_at, :updated_at 
end 

지금의 약자로서 내가 않고 새로운 바 개체를 만들 수없는 것 중 하나 내가 바 객체가 동의 할 수있는 방법 ...

을가 attr_protected 해제 또는 바 개체의이 공백 USER_ID 필요 attr_protected로부터 보호를 잃지 않고 foo의 user_id 속성? 일을

답변

2

시도 :

def create_bar 
    bar = Bar.build(... other params ...) 
    bar.user_id = user_id 
    bar.save! 
end 
+1

이것은 작동합니다! 고마워. 조니. 내 경우에는 bar = user.bar.build (... parameters)를 제외하고 –

2

attr_protectedattributes= 방법 느릅 나무의 속성을 필터는 new에 호출된다. 당신은 당신의 문제를 해결할 수 있습니다 :

def create_bar 
    returning Bar.new(other attributes) do |bar| 
    bar.user_id = user_id 
    bar.save! 
    end 
end 
+0

아! 나는 당신이 새로운 것을 빠져 나올 때까지 작동한다는 것을 알 수 있습니다. 그래서 다른 답변도 저에게 효과적이었습니다. –

+0

이 버전은 true/false가 아닌 예제의 개체를 반환합니다. – gaspard

관련 문제