1

Rails 4에는 strong_parameters가 포함되어 있습니다.이 중 큰 추가 기능이 있지만 문제가 있습니다. 나는 다형성 모델 Comment을 가지고 있으며, 필자가 필요로하는 매개 변수를 받아들이려면 컨트롤러를 사용할 수 없다.Rails 4의 다형성 모델에 ForbiddenAttributesError

경로 :

resources :articles do 
    resources :comments 
end 

모델 : 여기 (명확성을 위해 단축) 내 코드는

class Article < ActiveRecord::Base 
    has_many :comments, :as => :commentable 
end 

class Comment < ActiveRecord::Base 
    belongs_to :commentable, :polymorphic => true 
end 

컨트롤러 : 기사에 양식에서

class CommentsController < ApplicationController 
    before_action :get_commentable 

    def create 
    @comment = @commentable.comments.new(comment_params) 
    if @comment.save 
     redirect_to @commentable, :notice => "Thank you!" 
    else 
     render :new 
    end 
    end 

private 

    def get_commentable 
    resource, id = request.path.split("/")[1,2] 
    @commentable = resource.singularize.classify.constantize.find(id) 
    redirect_to :home unless defined?(@commentable) 
    end 

    def comment_params 
    params.require(:comment).permit(:title, :message) 
    end 
end 

게시 PARAMS (# 쇼) :

그것은 작동해야처럼3210
{"authenticity_token"=>"v70nN8aFpofNw9vbVjhpsm9SwLOwKlOpNOEOTozUwCk=", 
"comment"=>{"title"=>"Test","message"=>"Testing"}, 
"article_id"=>"1"} 

나에게 보이는, 그러나 무엇이든 나는 ActiveModel::ForbiddenAttributesError in CommentsController#create 얻을 시도 - 내가 컨트롤러에

def comment_params 
    params.permit! 
    end 

을 시도 할 경우에도. 나는 다른 (비 다형성) 모델에 그런 문제가 없기 때문에 그것이 다형성과 관련이 있다고 생각됩니다. 어떤 아이디어?

+0

사실,이 내가 역할 기반 권한 부여를 할 사용하고 캉캉으로 인한 오류가 보인다을 - 이를 사용 불가능으로 설정하면 주석을 작성할 수 있습니다. 흠. –

답변

2

답변이 없으므로 내가 여기 잘못된 나무를 짖고 있었다는 것을 나타내는 것처럼 보였습니다. 이 문제는 strong_parameters가 아니라 역할 및 작업 기반 권한 부여를 위해 사용하는 CanCan 보석과 관련이 있습니다. 분명히 CanCan이 객체에 매개 변수를 할당하는 방법과 관련이 있습니다 (CanCan이 기본 ActionController 메소드를 대신 함). 자세한 내용은 this bug report, 구체적으로 the reply from "rewritten"을 참조하십시오. 즉, 내 응용 프로그램 컨트롤러이 퍼팅하면 문제를 해결할 수 :

before_filter do 
    resource = controller_name.singularize.to_sym 
    method = "#{resource}_params" 
    params[resource] &&= send(method) if respond_to?(method, true) 
end 

업데이트 : 방법은 위의 관련이없는 컨트롤러에서 호출되는 경우

으로, @scaryguy 지적 모델이 넘어 질 것이다. 해결책은 간단히 메소드의 이름을 지정하고 before_filter로 호출하는 것입니다. 모델이없는 컨트롤러에서는이를 명시 적으로 제외하고 CanCan의 자동 기능 할당의 이점을 얻지는 못합니다.

before_filter :can_can_can 

def can_can_can 
    resource = controller_name.singularize.to_sym 
    method = "#{resource}_params" 
    params[resource] &&= send(method) if respond_to?(method, true) 
end 

그리고 모델이없는 컨트롤러 : I는 다음과 같이 계산한다

skip_before_filter :can_can_can 
+0

이것은 정확히 내가 가지고있는 것과 같은 문제 였고이 솔루션은 완벽하게 작동했습니다. 시간이 지날수록 더 많은 사람들이이 문제를 겪을 것입니다. – Ecnalyr

+0

감사합니다 @Ecnalyr, 그것이 누군가에게 도움이되었다는 것을 기쁘게 생각합니다! –

+0

예, 컨트롤러와 모델이 존재하고 둘 다 올바르게 명명 된 경우에만 작동합니다. 이것은 모델없이 컨트롤러를 사용하고자 할 때 문제가됩니다. – scaryguy

관련 문제