Not able to use new model with devise - ruby-on-rails

I have 2 models in my application ( Using rails 3.2.5)
1) User(From devise)
class User < ActiveRecord::Base
# 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
# attr_accessible :title, :body
has_many :profiles
end
2) Profiles.
class Profile < ActiveRecord::Base
belongs_to :user
attr_accessible :description, :name, :product, :image, :price
mount_uploader :image, ImageUploader
validates_presence_of :name, :product, :image, :price
end
There are many profiles of one user .
GOAL : I want to display only the profiles related to each user , when they login.
By reading rails document we can create a new profile for a user by (Code below), But this gives an error
"undefined method `Profile' for nil:NilClass"
Can somebody help me to define my controller's index,show,new,edit,create,update ,destroy or show me one and i can do it for all.
def new
#profile = #user.Profile.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #profile }
end
end

You are receiving this error because the #user is not initialized and is equal to nil so it has no method named profile, you should be using current_user helper of devise to get the current user #user = current_user.

Related

How to link/add models to each other

I'm trying to add idea(s) to a user. So far I added has_many to my user and belongs_to to my idea. And I added a foreign key to User using:
rails g migration Add_User_id_To_Ideas user_id:integer
Now, how do I assign the idea to the specific user, when a user creates a new idea?
I tried to work parallel to this example, but I'm a bit stuck.
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :ideas
end
idea.rb
class Idea < ActiveRecord::Base
belongs_to :user
has_many :comments
mount_uploader :picture, PictureUploader
# {attr_accessor :Status}
enum status: [ :Draft, :Published]
end
Several ways to do this, but I think the most straight forward way would be to save the user_id in the ideas controller create action.
# def create inside ideas_controller
#idea.user_id = current_user.id
if #idea.save
# etc
Couple other options are a hidden field or before_save callback. Here's an example of passing through a hidden field. In your #idea form:
<%= f.hidden_field :user_id, value: current_user.id %>
This will add user_id to the params being saved. Make sure that :user_id is whitelisted in the permitted params at the bottom of your ideas controller.
To permit user_id in idea_params:
def idea_params
params.require(:idea).permit(:user_id, :also_add_other_params)
end

2 different model login forms in single view, Rails 4 and Devise

I have created modal login forms for Advertisement and User. They are completely diferent from each other.
My goal is create ability to login as a user or advertisement in same view. So visitor selects to login as user -> user login form shows up and so on.
In some sources I read that I need to add some lines to Application_helper for ability to login as user from any place.
Application_helper.rb
def resource_name
:user
#tried thing below
:user, :advertisement # got syntax error from this line.
end
def resource
#resource ||= User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
I tried different variations of this code.
But no result.
My login forms looks like this :
<%= form_for(resource,:html => {id:"form-signin"}, as: resource_name, url: session_path(resource_name)) do |f| %>
....
<%end%>
I tried to use like:
<%= form_for(#advertisement,:html => {id:"form-signin"}, as: #advertisement, url: session_path(#advertisement)) do |f| %>
and
<%= form_for(#user,:html => {id:"form-signin"}, as: #user, url: session_path(#user)) do |f| %>
I got this error :Could not find a valid mapping for nil
User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :lockable
# confirmable
belongs_to :country
belongs_to :gender
has_many :reviews, :dependent => :destroy
acts_as_voter
acts_as_votable
validates :terms_of_service, acceptance: true
end
Advertisement.rb
class Advertisement < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:name]
include Humanizer
require_human_on :create
.......
end
Any help would be great.
Thanks.

Rails: undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class

I have a polymorphic relationship for my User model. I am using Devise.
When I try to edit the user's details, I get the following error:
undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class
The data submitted through the form is:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"Ap0JP2bs/w9J6iI9rZahiKR1K8UEIi7rp33a4OutMbo=",
"user"=>{"email"=>"some_email#yahoo.com",
"rolable"=>{"first_name"=>"Christopher",
"last_name"=>"Columbus",
"city"=>"16"}},
"commit"=>"Update"}
The controller method is:
def update
#user = User.find(current_user.id)
if #user.update_attributes(params[:user])
redirect_to edit_user_registration_path, notice: 'Your profile was successfully updated.'
else
redirect_to edit_user_registration_path, error: "Something went wrong, couldn't update your profile!."
end
end
The models:
1. User
class User < ActiveRecord::Base
belongs_to :rolable, :polymorphic => true
# Devise business
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :remote_avatar_url, :avatar, :login, :username, :email, :password, :password_confirmation, :remember_me
# For authenticating with facebook
attr_accessible :provider, :uid, :rolable
devise :omniauthable, :omniauth_providers => [:facebook]
# For authenticating with both username or email
attr_accessor :login
# Upload avatar
mount_uploader :avatar, AvatarUploader
# Makes username necessary
validates :username, :presence => true
end
2. Customer
class Customer < ActiveRecord::Base
has_one :user, :as => :rolable
has_one :preferences, :class_name => "CustomerPreferences"
belongs_to :city
attr_accessible :first_name, :last_name
end
What's the problem?
Based on your request hash, you are passing the rolable attribute as:
"rolable"=>{"first_name"=>"Cristian",
"last_name"=>"Gavrila",
"city"=>"16"}
You can't do this unless you specify that the User model accepts nested attributes for rolable. However, you have setup your User as belonging to a Rolable rather than the other way around. Nested attributes aren't designed to handle this inverse relationship - you may want to reconsider what you are trying to accomplish here, and modify the relationship accordingly.
For instance, you may want to turn your hash inside out and pass the rolable attributes with the user attributes embedded within. Or you may want to turn rolable into a has_one association.

How to get the current user that is logged in via active admin?

I would like to know how to get the current user that is logged in via the active admin GUI?
Homepage: http://www.activeadmin.info/
Thanks in advance
MODEL
admin_user.rb
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :id , :admin_permission
# attr_accessible :title, :body
has_one :admin_permission
validates_uniqueness_of :email
def self.current_logged_user
# ?
end
end
UPDATE
When I try to use the method 'current_user' in dashboard.rb or any active admin related file, apparently it is not implemented.
OUTPUT
undefined local variable or method `current_user' for
The active admin user is called AdminUser by default. The corresponding devise helper method is therefore current_admin_user.
reload the page and see in your terminal, in this case, puts the correct current_user logged email.
index do
column :name
column :email
column :slug
column :partner
puts current_user.email
default_actions
end
ActiveAdmin v1.x
index do
selectable_column
column :id
column :name
column :current_user_email do
current_user.try(:email)
end
actions
end

retrieve object id from relation in rails3

i have a model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :meetings, :dependent => :destroy do
def find_foreign
Meeting.where("user_id <> ?", id)
end
end
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
end
and when i am trying to get user's foreign meetings like that
some_user.meetings.find_foreign
i get an error
NoMethodError (undefined method `id' for []:ActiveRecord::Relation):
because self in find_foreign is an Array. How to retrive the User.id from this method ?
you can access self here:
def find_foreign
Meeting.where("user_id <> ?", self.id)
end
But don't know why you've written this?
some_user.meetings will already filter meetings by current user id. I've even no idea if block is allowed here!
find_foreign method is in User Model and you are trying to call it on Array of the Object of the Meetings
Just use
some_user.find_foreign

Resources