2012-04-23 2 views
1

메시지 모델과 사용자 모델이 있습니다. 내 메시지 belongs_to 내 사용자와 사용자 has_many 메시지.컨트롤러에 ID 값 전달, 대량 할당 보안 오류

사용자가 공개 프로필 페이지 (쇼 템플릿)에있는 동안 다른 사용자에게 비공개 메시지를 보내도록 허용하려고합니다. 나는 많은 시도를했지만 궁극적으로는 ID가 attr_accessible 인 것을 요구하는 문제로 되돌아 간다. 내가 뭔가 잘못하고 있는거야?

내 메시지 모델은 :user_id (현재 사용자, sending_from ID), :to_id, :content입니다.

나는 쇼 템플릿에, 사용자 프로필 페이지에서 찾고 있어요 내 사용자 show 액션에서

<%= form_for([current_user, @message]) do |f| %> 
     <%= f.hidden_field :to_id, :value => @user.id %> 
     <div class="field"> 
      <%= f.text_area :content, placeholder: "Send a private message..." %> 
     </div> 
     <%= f.submit "Post", class: "btn btn-large btn-primary" %> 
    <% end %> 

는이 양식을 제출하면, 나는 간다,

def show 
    @user = User.find(params[:id]) 
    @microposts = @user.microposts.paginate(page: params[:page]) 
    if user_signed_in? 
     @message = current_user.messages.build(params[:messages], to_id: @user.id) 
    end 
end 

이 내 메시지에 난 항상 오류가,

def create 
    @message = current_user.messages.build(params[:message]) 
    redirect_to user_path(params[:message][:to_id]) 
end 

그러나 조치를 작성

`Can't mass-assign protected attributes: to_id` 

:to_id attr_accessible으로 해결할 수있는 것처럼 보이지만 그렇게하는 것이 안전하지 않다고 들었습니다. 내가 뭔가 잘못하고 있는거야? 이 문제로 저를 죽였습니다.

도움을 주시면 감사하겠습니다. 감사합니다

+0

나는이 편집되기 전에, 당신은 몇 가지 [Alots] (http://hyperboleandahalf.blogspot.com 처리해야 할 것 : 그런 식으로 일을하는 이유는 다음과 같은 추가 화이트리스트 매개 변수를 추가 할 수 있습니다 /2010/04/alot-is-better-than-you-at-everything.html)! –

답변

2

to_id에 액세스 할 수 있도록 설정하는 것이 좋습니다. 당신이 그 오류를 원하지 않는 경우 그러나 단지 이런 식으로 문제를 해결 :

def create 
    @message = current_user.messages.build 
    @message.to_id = params[:message][:to_id] 
    # manually assign whatever other params you need to 
    redirect_to user_path(params[:message][:to_id]) 
end 

질량 할당은 당신이, 당신은 여전히 ​​model.attribute=을 사용할 수 있습니다 update_attributes를 사용할 수 없음을 의미합니다.

def create 
    safe_params = params[:model].slice(:safe_attr1,:safe_attr2) 
    @model = Model.new(safe_params) 
    whitelist = ['some_safe_string','another_safe_string'] 
    if whitelist.include?(params[:model][:dangerous]) 
    @model.dangerous_attribute = params[:model][:dangerous] 
    end 
    @model.save 
    redirect_to @model 
end 
+0

다시 도움을 주셔서 감사합니다.) 및 설명에 감사드립니다. 그것은 매우 도움이되었습니다. 나는 처음에는 내가 그것을 만들지 않으면 어떤 식 으로든 구원 할 수 없다고 생각했다. attr_accessible – Sasha