Skip to content

Commit

Permalink
Merge pull request ryanb#653 from andhapp/fix-pull-request-640
Browse files Browse the repository at this point in the history
Init attributes in InheritedResources controller w/ specs
  • Loading branch information
ryanb committed Jun 19, 2012
2 parents aff8ca6 + a1254ca commit 2b89dbb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/cancan/controller_resource.rb
Expand Up @@ -83,6 +83,10 @@ def load_collection

def build_resource
resource = resource_base.new(resource_params || {})
assign_attributes(resource)
end

def assign_attributes(resource)
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
initial_attributes.each do |attr_name, value|
resource.send("#{attr_name}=", value)
Expand Down
3 changes: 2 additions & 1 deletion lib/cancan/inherited_resource.rb
Expand Up @@ -6,7 +6,8 @@ def load_resource_instance
@controller.send :association_chain
@controller.instance_variable_get("@#{instance_name}")
elsif new_actions.include? @params[:action].to_sym
@controller.send :build_resource
resource = @controller.send :build_resource
assign_attributes(resource)
else
@controller.send :resource
end
Expand Down
18 changes: 18 additions & 0 deletions spec/cancan/inherited_resource_spec.rb
Expand Up @@ -39,4 +39,22 @@
CanCan::InheritedResource.new(@controller).load_resource
@controller.instance_variable_get(:@projects).should == :projects
end

it "should build a new resource with attributes from current ability" do
@params[:action] = "new"
@ability.can(:create, Project, :name => "from conditions")
stub(@controller).build_resource { Struct.new(:name).new }
resource = CanCan::InheritedResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "from conditions"
end

it "should override initial attributes with params" do
@params.merge!(:action => "new", :project => {:name => "from params"})
@ability.can(:create, Project, :name => "from conditions")
stub(@controller).build_resource { Struct.new(:name).new }
resource = CanCan::ControllerResource.new(@controller)
resource.load_resource
@controller.instance_variable_get(:@project).name.should == "from params"
end
end

0 comments on commit 2b89dbb

Please sign in to comment.