naveed
naveed

Reputation: 23

Update Cancan in rails

im doing an authorisation application where: -have admin role, who can manage everything. -have guest role, who can create posts and edit the posts which he has created.

im facing problem with the guest role. I have done associations where: -posts belongs_to user(In post model am having user_id attribute also in migration i have referenced posts to users) -user has_many posts.

when im tryin to create a new post, the user_id is nil. i dunno how to set user_id attribute in Post object.

class ProductsController < ApplicationController

before_filter :self_load, :only=>[:show,:edit,:update,:destroy]

before_filter :authenticate_user, :only=>[:edit,:update,:destroy]

def index
 @products=Product.find(:all)
end

def new 
 @product=Product.new(:user_id=>current_user.id)
end


def create
 @product=Product.new(params[:product])
 if @product.save
    redirect_to root_url, :notice=>'New Product has been added'
 else
    render :action=>'new'

 end
end  

def show
end

def edit
end

def update

if @product.update_attributes(params[:product])
     redirect_to root_url, :notice=>'Product has been updated.'
  else
     render :action => 'edit'
  end
end


def destroy

 @product.destroy
 redirect_to root_url    
end

def self_load
 @product = Product.find(params[:id])
end

def authenticate_user
 if current_user
 else
   redirect_to root_url, :notice=>'You are not authorised to access'
 end
end
end

view:

Add Product

<%= form_for(@product) do |f| %> <% if @product.errors.any? %>

  <ul>
  <% @product.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
<% end %>

<table>

<tr><td><%= f.label 'Title:' %></td>
   <td><%= f.text_field :title %></td>

<tr><td><%= f.label 'Description:' %></td>
  <td><%= f.text_area :description,:rows=>10 %></td></tr>

<tr><td><%= f.label 'Price:' %></td>
   <td><%= f.text_field :price %></td></tr>

<tr><td><%= f.submit 'Save' %></td></tr>
</table>

<% end %>
<%= link_to 'Back', root_url %>

Model class Product < ActiveRecord::Base

 belongs_to :user 

 attr_accessible :title, :description, :price, :user_id

 validates_presence_of :title, :description, :price

 validates_uniqueness_of :title

 validates_length_of :title, :in=>4..10

 validates_length_of :description, :minimum=>10

 validates_numericality_of :price
end

Plz help me with this.... if u need any further info u can ask...

Upvotes: 0

Views: 112

Answers (1)

Naveed
Naveed

Reputation: 11167

if only signed in user can create products, try this

class ProductsController < ApplicationController
  def create
    @product =  current_user.products.build params[:product]

    if @product.save
      # Stuff is product save succesfully
    else
      # Stuff is product does not saved
    end

  end
end

Upvotes: 1

Related Questions