Hey I'm struggling a bit with the active admin setup related to my user model. I'm using devise.
When I click on the User tab in active admin I get:
NoMethodError in Admin/users#index
Showing /Users/bweidlich/.rvm/gems/ruby-1.9.3-p286/gems/activeadmin- 0.5.1/app/views/active_admin/resource/index.html.arb where line #1 raised:
undefined method `user_id_contains' for #<MetaSearch::Searches::User:0x007fc0a9831cf8>
Extracted source (around line #1):
1: insert_tag renderer_for(:index)
and when I want to edit one particular user I get:
NoMethodError in Admin/users#edit
Showing /Users/bweidlich/.rvm/gems/ruby-1.9.3-p286/gems/activeadmin-0.5.1/app/views/active_admin/resource/edit.html.arb where line #1 raised:
undefined method `user_id' for #<User:0x007fc0a47d3e28>
Extracted source (around line #1):
1: insert_tag renderer_for(:edit)
Does anyone have an idea where I should look for the error?
As always, any help would be greatly appreciated!
Thanks guys
EDIT:
App user model
class User < ActiveRecord::Base
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
attr_accessible :role_ids, :as => :admin
attr_accessible :username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :avatar, :bio, :title, :company,:facebook,:twitter,:pinterest,:linkedin
validates_presence_of :username
validates_uniqueness_of :username, :email, :case_sensitive => false
has_many :events
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :followed_users, through: :relationships, source: :followed
has_many :comments
has_one :avatar
def update_without_password(params={})
params.delete(:current_password)
super(params)
end
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
end
active admin user model:
ActiveAdmin.register User do
form do |f|
f.inputs "User Details" do
f.input :email
f.input :password
f.input :password_confirmation
f.input :superadmin, :label => "Super Administrator"
end
f.buttons
end
create_or_edit = Proc.new {
#user = User.find_or_create_by_id(params[:id])
#user.superadmin = params[:user][:superadmin]
#user.attributes = params[:user].delete_if do |k, v|
(k == "superadmin") ||
(["password", "password_confirmation"].include?(k) && v.empty? && !#user.new_record?)
end
if #user.save
redirect_to :action => :show, :id => #user.id
else
render active_admin_template((#user.new_record? ? 'new' : 'edit') + '.html.erb')
end
}
member_action :create, :method => :post, &create_or_edit
member_action :update, :method => :put, &create_or_edit
end
users table schema
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(255)
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# username :string(255)
# bio :text
# title :string(255)
# company :string(255)
# facebook :text
# twitter :text
# pinterest :text
# linkedin :text
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# first_name :string(255)
# last_name :string(255)
# avatar :string(255)
# avatar_id :integer
#
Related
I have been trying to integrate raytrate into ActiveAdmin when trying to include the partial into my Activeadmin supply_company.rb it apears to be unable to find the 'current_user'. I know that with a standard install of ActiveAdmin and devise I have left the admin user as admin_user so should be able to use current_admin_user to set the current user. I have a suspicion it the way in which I'm trying to include the render in the sidebar.
Or if anyone has an alternative model for rating that they know works in ActiveAdmin I would gladly take a look at it.
The error message is
ActionView::Template::Error (undefined local variable or method `current_user' for #<#:0x6b50a58>):
app/controllers_rater_controller.rb
class RaterController < ApplicationController
def create
if admin_user_signed_in?
obj = params[:klass].classify.constantize.find(params[:id])
obj.rate params[:score].to_f, current_admin_user, params[:dimension]
render :json => true
else
render :json => false
end
end
end
app/models/admin_user.rb
class AdminUser < ActiveRecord::Base
rolify
has_one :profile, foreign_key: :admin_user_id
accepts_nested_attributes_for :profile
has_many :addresses
has_many :address_types, :through => :addresses
accepts_nested_attributes_for :addresses
ratyrate_rater
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb =>
"100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end
app/models/supply_companies.rb
class SupplyCompany < ActiveRecord::Base
has_many :products, :through => :product_supply_companies
has_many :product_supply_companies, :foreign_key => 'supply_company_id'
accepts_nested_attributes_for :products
accepts_nested_attributes_for :product_supply_companies, :allow_destroy => true
ratyrate_rateable "communication", "quality", "price"
end
/app/admin/supply_company.rb
ActiveAdmin.register SupplyCompany do
permit_params :id, :company_name,
products_attributes: [:id, :product_name, :product_description],
product_supply_companies_attributes: [:id, :product_id],
supply_company_ratings_attributes: [:id, :admin_user_id, :supply_company_id, :supply_company_rating ],
admin_user_attributes: [:id]
index do
column :id
column :company_name
column :products do |pt|
pt.products.collect {|c| c.product_name.capitalize }.to_sentence
end
actions
end
filter :company_name
form(:html => {:multipart => true}) do |f|
f.inputs "Company Details" do
f.input :company_name
end
f.actions
end
show title: :company_name do
attributes_table do
row :company_name
end
end
sidebar "Products", only: :show do
attributes_table_for supply_company do
row "Ratings" do
render 'supply_company_ratings'
end
row :products do |pt|
pt.products.collect {|c| link_to c.product_name.capitalize, admin_products_path + "\/" + c.id.to_s}.join(", ").html_safe
end
end
end
end
app/views/admin/supply_companies/_supply_companines_ratings.html.erb
<h2>Communication :</h2> <%= rating_for #supply_company, "communication" %>
<h2>Engine :</h2> <%= rating_for #supply_company, "quality" %>
<h2>Price :</h2> <%= rating_for #supply_company, "price" %>
Sound's like you have installed ratyrate with rails g ratyrate user, you need to install it with rails g ratyrate admin_user.
I cleaned up my code, it looks much nicer now, but still doesn’t work. It starts to be a pain…
I just can’t save a parent with an existing child in nested form with parent has_many childs :through joinmodel.
In my case a Project has_many contributing Teachers and many contributing Pupils, both are Join-Models to Users. A Project has_many Schools as well.
(May be I should better name the models Teacherize and Pupilize or ProjectTeacher and ProjectPupil.)
As long as all records are new it all works fine. As soon as I want to connect an existing User as new Teacher of a new Project I get the following error:
Couldn't find User with ID=1 for Teacher with ID=
(1 is the correct user ID)
The problem should be somewhere her in my helper to setup empty form fields:
At least I guess so...
module ProjectsHelper
def setup_project(project)
if project.teachers.length <= 0 # usually there is just one teacher, so add one if there isn't one
teacher = project.teachers.build(:role_in_project => 'master')
if user_signed_in?
#teacher = project.teachers.new(:role_in_project => 'master', :user => current_user)
teacher.user = current_user # associate first teacher with current_user
else
#teacher = project.teachers.build
teacher.user = User.new # associate first teacher with a new user instance
end
end
if project.project_schools.length <= 0 # usually there is just one school, so add one if there isn't one
project_school = project.project_schools.build
project_school.school = School.new
end
if project.pupils.length < 3 # There can be up to 3 people, so add a blank fieldset as long as there are less than 3
pupil = project.pupils.build
pupil.user = User.new
end
project
end
end
These are my params received:
{"utf8"=>"✓", "authenticity_token"=>"uCCMk/s3SpDfR7+fXcsCOHPvfvivBQv8pVFVhdh6iro=",
"project"=>{
"teachers_attributes"=>{
"0"=>{
"id"=>"",
"user_attributes"=>{
"id"=>"1",
"gender"=>"male",
"title"=>"",
"firstname"=>"Firstname1",
"name"=>"Lastname1",
"faculty"=>"",
"fon"=>"",
"fax"=>""}
}
},
"id"=>"",
"title"=>"First Project",
"description"=>"This is a foo bar project!",
"presentation_type"=>"experimentell",
"note"=>""
},
"commit"=>"Register Project",
"action"=>"create",
"controller"=>"projects"
}
The case isn’t too abstract; it has to be possible to achieve it.
It’s just to connect a new parent record with an existing child record!
In this article, which is very good, exactly the case is explaint:
http://rubysource.com/complex-rails-forms-with-nested-attributes
# app/helpers/form_helper
module FormHelper
def setup_user(user)
user.address ||= Address.new
(Interest.all - user.interests).each do |interest|
user.interest_users.build(:interest => interest)
end
user.interest_users.sort_by! {|x| x.interest.name }
user/tmp/clean-controllers.md.html
end
end
There the interest is existing and gets connected through a new record in interest_uesers.
Why do I get the error when trying to do the same thing?
project.teachers.build(:user => current_user)
I studied several articles and casts, but none of them connect existing childs.
http://railscasts.com/episodes/196-nested-model-form-revised
http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Rails 3.1+ Nested Forms Issue: Can't mass-assign protected attributes
Trying to use accepts_nested_attributes_for and has_and_belongs_to_many but the join table is not being populated
Quote: “accepts_nested_fields_for is used to create and modify related objects in a form. It can be used to populate join table, which is kind of what you're trying to do. However, using accepts_nested_fields_for to populate the join table is impossible with a HABTM relationship.”
That’s what I wanna do! Populate the join table!
It starts to be frustrating and I’d be glad to get some help!
My Models
class Project < ActiveRecord::Base
attr_accessible :title, :description, :presentation_type, :note,
:project_schools_attributes, :schools_attributes, :teachers_attributes, :pupils_attributes,
:users_attributes
validates_presence_of :title
validates_presence_of :description
validates_presence_of :presentation_type
has_many :project_schools, :dependent => :destroy
accepts_nested_attributes_for :project_schools
has_many :schools, :through => :project_schools
#accepts_nested_attributes_for :schools, :reject_if => :all_blank
has_many :pupils, :dependent => :destroy
accepts_nested_attributes_for :pupils, :reject_if => :all_blank
has_many :users, :through => :pupils
has_many :teachers, :dependent => :destroy
accepts_nested_attributes_for :teachers, :reject_if => :all_blank
has_many :users, :through => :teachers
#accepts_nested_attributes_for :users, :reject_if => :all_blank
end
class ProjectSchool < ActiveRecord::Base
attr_accessible :role_in_project, :comment,
:school_attributes, :school_id, :project_id
belongs_to :school
accepts_nested_attributes_for :school
belongs_to :project
end
class School < ActiveRecord::Base
attr_accessible :email, :fax, :fon, :name, :place, :street, :type_of_school, :www, :zip
has_many :project_schools
has_many :projects, :through => :project_schools
has_many :users # in real live they are named teachers and pupils but in this case the association goes directly to a user_id, not to teacher/pupil model
validates_presence_of :name, :type_of_school, :street, :place, :zip, :fon
validates :email, :format => { :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }, :allow_blank => true
end
class Teacher < ActiveRecord::Base
attr_accessible :role_in_project, :user, :user_attributes, :project_id, :user_id
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :user
serialize :role_in_project
end
class Pupil < ActiveRecord::Base
attr_accessible :classname, :user_attributes #, :project_id, :user_id
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :user
end
class User < ActiveRecord::Base
serialize :roles
belongs_to :school
has_many :teachers
has_many :pupils
has_many :projects, :through => :teachers
has_many :projects, :through => :pupils
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :gender, :firstname, :name, :street, :place, :title, :faculty, :assignment,
:classname, :zip, :fon, :fax, :school_id, :roles,
:password, :added_by_user_id, :password_confirmation, :remember_me
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable#, :validatable
after_initialize :init
def init
# the default guest user
self.roles ||= ['default'] #will set the default value only if it's nil
end
end
My controller
class ProjectsController < ApplicationController
require 'axlsx'
before_filter :load_page, only: [:show, :index, :destroy]
def new
#project = Project.new
end
def create
#project = Project.new(params[:project])
respond_to do |format|
if #project.save
sign_in(:user, #project.teachers[0].user) unless user_signed_in?
# TODO: send mail
# save as excel file in dropbox
save_in_dropbox(#project)
format.html { redirect_to #project, notice: t('project.was_created') }
else
logger.debug #project.errors.inspect
format.html { render action: "new" }
end
end
end
end
projects/_form.html.haml
%h1
= t('project.register_headline')
= simple_form_for( setup_project(#project), :html => {:class => 'form-horizontal'} )do |f|
= f.error_notification
#teachers-wrapper.well
%span.jumpanchor#lehrkraft_anchor
%fieldset.form-inputs
= f.simple_fields_for :teachers do |teacher|
= render "teacher_fields", :f => teacher
.school-wrapper.well
%span.jumpanchor#schule_anchor
%h2
Informationen zur Schule
%fieldset.form-inputs
= f.simple_fields_for :project_schools do |project_school|
= render "school_fields", :f => project_school
.project-wrapper.well
%span.jumpanchor#projekt_anchor
%h2
Informationen zum Projekt der Schüler
%fieldset.form-inputs
= f.hidden_field :id
= f.input :title, :input_html => { :class => 'span6' }
= f.input :description, :input_html => { :class => 'span6', rows: 5 }
= f.input :presentation_type, collection: ['theoretisch', 'experimentell'], as: :radio_buttons, :class => 'controls-row', :input_html => { :class => 'inline' }
.clearfix
= f.input :note, :input_html => { :class => 'span6', rows: 3 }
.pupils-wrapper.well
%span.jumpanchor#schuler_anchor
%fieldset.form-inputs
= f.simple_fields_for :pupils do |pupil|
= render "pupil_fields", :f => pupil
projects/_teacher_fields.html.haml
= f.simple_fields_for :user do |user|
=# render "teacher_user_fields", :f => user
%h2
Betreuende Lehrkraft
- if user_signed_in?
= user.input :email, :disabled => true, :input_html => {:class => 'email_validation'}
- else
= user.input :email, :autofocus => true, :input_html => {:class => 'email_validation'}, :hint => 'Dies muß Ihre eigene E-Mailadresse sein!'
.details
=# user.hidden_field :id
= user.input :id
= user.input :gender, collection: [:female, :male]
= user.input :title
= user.input :firstname
= user.input :name
= user.input :faculty
= user.input :fon
= user.input :fax
It is Rails 3.2 with Ruby 1.9.3
I want to add the current_user.id from devise to another model...
question model:
class Question < ActiveRecord::Base
belongs_to :user
attr_accessible :content
validates :content, :presence => true
end
user model:
class User < ActiveRecord::Base
has_many :questions
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
my question migration:
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.string :content
t.date :deadline
t.integer :user_id
t.timestamps
end
end
end
In my questions controller:
def create
params[:question][:user_id]=current_user.id
#question = Question.new(params[:question])
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
When i save the question the current_user.id won't be recorded in my database?
Try this instead:
def create
#question = Question.new(params[:question])
#question.user_id = current_user.id
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
I am getting this error:
2011-04-09T18:13:17+00:00 app[web.1]: NameError (uninitialized constant Group::Membership):
2011-04-09T18:13:17+00:00 app[web.1]: app/controllers/groups_controller.rb:25:in `show_members'
When I try and use the Show_members method in the groups controller. What have I done wrong?
user.rb
class User < ActiveRecord::Base
require 'paperclip'
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
has_and_belongs_to_many :roles
has_many :articles
has_many :ratings
has_many :rated_articles, :through => :ratings, :source => :articles
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
...
membership.rb
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
validates_uniqueness_of :user_id, :message => "You can only join one group!"
end
group.rb
class Group < ActiveRecord::Base
require 'paperclip'
attr_accessible :name, :group_admin, :about, :location, :created_at, :avatar
validates_uniqueness_of :name, :group_admin
validates_length_of :name, :in => 4..40
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
end
group_controller
def show_members # members page
#group = Group.find(params[:id])
#members = #group.users <= THIS LINE IS THE ERROR
#group_admin = User.find(#group.group_admin)
respond_to do |format|
format.html
format.xml { render :xml => #group }
end
end
Update
def remove_user
#membership = Membership.find(params[:user_id, :group_id])
#membership.destroy
authorize! :remove_user, #membership
respond_to do |format|
format.html { redirect_to(:back, :notice => 'User was successfully Removed.') }
format.xml { head :ok }
end
I have this action in the groups_controller linked to in the show_members.html.erb
could the error be coming from this?
Oh my god. I just checked the git logs. Apparently, git decided not to add the memberships model file to the repo for some reason despite me doing git commit -a -m"blah". I thought the -a flag added everything?
I don't see an error in the code you pasted, but judging from the error code you get, you must be having a constant value somewhere that cannot be accessed. Do you have any Group.Membership call somewhere in your code ? (maybe a module?) Maybe you meant to write group.membership or something. I really can't spot anything else :/
EDIT :
Btw, i see something that should be causing a problem as well :
#group_admin = User.find(#group.group_admin)
group.admin is a name as a i see in your validations and you're looking up for an id. It should be find_by_group_admin in this one.
I have three models for users. User, role & assignments. This is how the models look:
assignment.rb
# == Schema Information
# Schema version: 20101117094659
#
# Table name: assignments
#
# id :integer not null, primary key
# created_at :datetime
# updated_at :datetime
# user_id :integer
# role_id :integer
#
class Assignment < ActiveRecord::Base
belongs_to :role
belongs_to :user
end
role.rb
# == Schema Information
# Schema version: 20101117094659
#
# Table name: roles
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
#
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
user.rb
# == Schema Information
# Schema version: 20110102225945
#
# Table name: users
#
# id :integer primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# username :string(255)
# f_name :string(255)
# l_name :string(255)
#
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, and :lockable
devise :database_authenticatable, :registerable, :timeoutable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_and_belongs_to_many :projects
has_many :stages
has_many :uploads
has_many :comments
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
end
In my view, to select the projects for the current user, I do this:
In my projects controller, I have:
def index
#projects = current_user.projects
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #projects }
end
end
Then in the view I do this:
<% if current_user.projects.exists? %>
<div class="data">
There are <%= current_user.projects.count %> projects.<br />
<table>
<% current_user.projects.each do |project| %>
<tr class="changer">
<td><%= link_to project.name, project %></td>
</tr>
<% end %>
</table>
</div>
<% else %>
<div class="no-data">
<%= image_tag('create-project-icon.png') %><br />
Create Project
</div>
<% end %>
The users have 4 roles: Designer, Client, Admin, Superuser.
Each designer can have multiple clients. Each client can also belong to multiple designers.
So I guess I have two questions:
If the currently logged in user (a designer) wants to add a client (they can only add clients, no other user type), how do I do that? What's the syntax I will use according to my code samples above. Once I add a client, I will want to associate him to projects, stages, uploads and comments. So in theory, 1 designer will have multiple projects which will belong to multiple clients.
How do I then retrieve the clients only, for the designer logged in. i.e. how do I select all the users with role client associated with the current_user ?
Thanks.
The question was...given that users (clients) have already been added
to a project owned by another user (a designer), how do I retrieve
those users
That is pretty straight forward :
# Given a project #project = Project.find(id)
#clients = #project.users.joins(:roles).where("roles.name = 'client'")