I check the docs but it only works when include 1 more global role.
how can I do multiple role checking without global role?
user.add_role :admin
user.add_role(:user, group)
user.add_role(:mentor, group)
user.has_all_roles? :admin, {:name => :mentor, :resource => group}
=> true
user.has_all_roles? {:name => :mentor, :resource => group}, {:name => :user, :resource => group}
=> SyntaxError: (irb):27: syntax error, unexpected =>, expecting '}'
user.has_any_role? :admin, {:name => :mentor, :resource => group}, {:name => :user, :resource => group}
=> true
user.has_any_role? {:name => :mentor, :resource => group}, {:name => :user, :resource => group}
=> SyntaxError: (irb):30: syntax error, unexpected =>, expecting '}'
Very annoying, but simply solved! Reason is that by writing
user.has_all_roles? {...}
you tell ruby: I'm giving a block to this method call... And that's obviously not what you want.
Simple fix: just add parentheses to your method call:
user.has_all_roles?( {...} )
Related
I have a nested models set :
class Event < ActiveRecord::Base
belongs_to :place
:place
attr_accessible :place_attributes, :reject_if => :all_blank, :allow_destroy => false
class Place < ActiveRecord::Base
has_many :events
validates :label, :presence => true,
:uniqueness => {:case_sensitive => true, :on => :create }
validates :description, :presence => {:on => :create},
:uniqueness => {:case_sensitive => true , :on => :create}
In a test scenario, w the nested form, the user can update only the Place#label attributes, keeping all the other information..
test "should_update_event_place_data" do
put :update, :locale => I18n.locale, :id => #event[:id],
:event => { :place_attributes => { label: "a very beautiful place" } }
which leads to a request to EventsController#update, receiving the parameters :
params
{"event"=>{"place_attributes"=>{"label"=>"a very beautiful place"}}, "locale"=>"en",
"id"=>"145", "controller"=>"backoffice/events", "action"=>"update"}
(rdb:1) #event.update_attributes(params[:event])
false
#messages={:"place.description"=>["cannot be blank"]
But the validation is on create , not update .... no validation error should be detected ..
what could be wrong ?
thanks for help
I did more testing
debugger , right after the test setup ( before sending the put request)
#event_0
#<Event id: 161, account_id: 3, place_id: 249, slug: "my-new-event-on-2013-01-01-at- edinburgh-united-king...", title: "My New Event"
#event_0.place
#<Place id: 249, label: "new fake place",..
test request:
put :update, :locale => I18n.locale, :id => #event_0[:id], :event => { :place_attributes => { label: "a very beautiful place"} }
params in request are OK, #request/method = PUT
In EventsController#update
#event.update_attributes(params[:event])
.... I inserted a debug in the Place model...
(before_validation :i_am_on_create, :on => :create)
def i_am_on_create
debugger
p "CREATING"
end
and it's creating !! don't understand why it's not updating the parent nested model
update_attributes does not propagate the updates to associations. If you watch the source code (http://apidock.com/rails/ActiveRecord/Base/update_attributes) you'll see that the #save
is called in the end. And this is the default behaviour:
# existing resource 'mazeratti car'
car.name = "Wheelz"
car.brand.label = "Ferrari"
car.save
car.reload
car.name #=> "Wheelz"
car.brand.label #=> "Mazeratti"
if you want associations to be updated all the time the object is updated, look into using "autosave" (http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to : Options)
If you're only wanting to test that the label attribute is updated, why not try doing update_attribute on that field only rather than the whole 'event'? Something like:
#event.place_attributes.update_attribute(
:label => params[:event][:place_attributes][:label]
)
Not tested - but you get the idea...
SOLVED
in order to update the nested model, I need to add the model instance id :
put :update, :locale => I18n.locale, :id => #event_0[:id], :event => { :place_attributes => { id: #event_0.place[:id], label: "a very beautiful place"} }
so in :place_attributes , I added the existing #event_0.place[:id] , and it's now updating
I found it in Anson answer on Feb 17 at 17:04 bottom page at
accepts_nested_attributes_for with find_or_create?
I have 2 tables User and Member and there relation is
In user
has_one :member, :class_name => 'User::Member'
Member
belongs_to :user
I am trying to insert data using console and I am using this code
u = User.create(
:group => UserGroup.find_by_slug(:members),
:first_name => 'abc',
:last_name => 'fgh',
:company_name => 'xyz',
:email => 'test#test.com',
:password => '123456',
:password_confirmation => '123456'
)
m = User::Member.create(
:user => u,
:pricing_plan => PricingPlan.order('RANDOM()').first,
:state => UserState.order('RANDOM()').first,
:industry => Industry.order('RANDOM()').first,
:fy_start_month => 7
)
It is throwing this error
syntax error, unexpected tIDENTIFIER, expecting $end
) m = User::Member.create(
I am wondering what is wrong with my syntax.Thanks in advance
This may be due to an invisible char (not whitespace). Your syntax seems to be ok, but if your editor allows you to show invisibles (in textmate, for example, go to view > show invisibles, try to do that. It sometimes happens to me that I insert invisibles instead of whitespace.
To give you an impression what I am talking about:
This is invisibles hidden
This is invisibles shown. The invisible lozenges you do not see in normal mode cause a syntax error:
I am assuming user_id is your foreign key which is associated with the users table.
If so use following
m= Member.create(
:user_id => u.id,
:pricing_plan => PricingPlan.order('RANDOM()').first,
:state => UserState.order('RANDOM()').first,
:industry => Industry.order('RANDOM()').first,
:fy_start_month => 7
)
try this
In your User Model
has_one :member
attr_accessible :member_attributes
accepts_nested_attributes_for :member
In your Member Model
belongs_to :user
then try in your console as well as your form
user = User.create(
:group => UserGroup.find_by_slug(:members),
:first_name => 'abc',
:last_name => 'fgh',
:company_name => 'xyz',
:email => 'test#test.com',
:password => '123456',
:password_confirmation => '123456'
)
and
user.build_member(
:pricing_plan => PricingPlan.order('RANDOM()').first,
:state => UserState.order('RANDOM()').first,
:industry => Industry.order('RANDOM()').first,
:fy_start_month => 7
)
or
member = Member.create(
:user_id => user.id,
:pricing_plan => PricingPlan.order('RANDOM()').first,
:state => UserState.order('RANDOM()').first,
:industry => Industry.order('RANDOM()').first,
:fy_start_month => 7
)
There is a mass assignment defined in sys_log model in our rails 3.1.4 app:
attr_accessible :log_date, :user_name, :user_id, :user_ip, :action_logged, :as => :new_log
A method is defined in application_controller to save the log:
def sys_logger(action_logged)
log = SysLog.new(:log_date => Time.now, :user_id => session[:user_id], :user_name => session[:user_name], :user_ip => session[:user_ip],
:action_logged => action_logged, :as => :new_log)
log.save
end
However, the mass assignment does not work. Here is the warning message:
WARNING: Can't mass-assign protected attributes: log_date, user_id, user_name,
user_ip, action_logged, as
:new_log is not working as defined. What's wrong with the code above? Thanks so much.
The :as => :new_log is now part of the hash of attributes, instead of a separate option you pass in.
Adding some curly braces should help:
def sys_logger(action_logged)
log = SysLog.new({:log_date => Time.now, :user_id => session[:user_id],
:user_name => session[:user_name], :user_ip => session[:user_ip],
:action_logged => action_logged }, :as => :new_log)
log.save
end
Or assigning it temporarily:
def sys_logger(action_logged)
attrs = { :log_date => Time.now, :user_id => session[:user_id],
:user_name => session[:user_name], :user_ip => session[:user_ip],
:action_logged => action_logged }
log = SysLog.new(attrs, :as => :new_log)
log.save
end
going directly to my problem.
render :json => projects.to_json(:only => ['name', 'id'],:include => {:client => {:only => ['name']}, :deliverables => {:only => ['name', 'id'], :include => {:tasks => {:only => ['name','id']} } } })
This is how my controller responds for json request. Now my problem is that it lists all the deliverables & tasks that are in given project but here I want to respond with tasks & deliverables that meets certain condition like all that are created in specific month.
Thanks is advance.
Here's what I did, in project model
has_many :uncompleted_deliverables,
:class_name => 'Deliverable',
:conditions => 'completed = false'
The same applies to deliverable model
has_many :uncompleted_tsks, :class_name => 'Task', :conditions => 'completed = false'
And then responded json in following way,
format.json { render :json => projects.to_json(:only => ['name', 'id'],
:include => {:client => {:only => ['name']}, :uncompleted_deliverables => {:only => ['name', 'id'], :include => {:uncompleted_tsks => {:only => ['name','id']} } } }) }
Anyway thanks guys for your response..
Could you just include a proc? (see end of documentation here)
I guess the code could look something like that:
in you Project model:
def to_json(options={})
tasks_json = Proc.new { |options|
options[:builder].tasks do
selected_tasks = tasks.select {|t| t.created_at > 30.days.ago } # or whatever your condition is
selected_tasks.each do |t|
options[:builder].task do
options[:builder].tag!('id', t.id)
options[:builder].tag!('name', t.name)
end
end
end }
options.merge!(:procs => [tasks_json])
end
Would that work for you?
I have two models
class Group < AR
has_many :permissions
accepts_nested_attributes_for :permissions, :allow_destroy => true
end
class Permission < AR
validates_uniqueness_of :action, :scope => [:role]
end
I can't seem to get the unique constraint on permissions to work when creating a new group, only on update. Here's a sample output. Does anyone know the best way to get validation to work on nested attributes and unique constraints?
sample output
> g = Group.create(:permissions_attributes => [{:role => 'admin', :action => 'one'}])
> # Now add the same permissions, should not be valid
> g.permissions_attributes = [{:role => 'admin', :action => 'one'}]
> g.valid? # => false
That is expected. However if I create the Group with the same permissions_attributes twice, it doesn't invalidate:
> g = Group.new(:permissions_attributes => [{:role => 'admin', :action => 'one'}, {:role => 'admin', :action => 'one'}]
> g.valid? # => true BUT THIS SHOULD BE FALSE!!
> g.save # => true Oh Nos!!!
class Group < AR
has_many :permissions
accepts_nested_attributes_for :permissions, :allow_destroy => true
validates_associated :permissions
end