devise rails adding user_id to another model - ruby-on-rails-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

Related

ActiveAdmin Ratyrate unable to find current_user OR Alternative

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.

Updating a model from another controller

I would like to update the "User" model which has a column named "verification_code_confirmation" from the "Verifications" Controller
I had tried writing this code
class VerificationController < ApplicationController
def index
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
redirect_to #user, :flash => { :success => "Successfully verified." }
else
render :action => 'edit'
end
end
and
index.html.erb for verifications view.
<%= form_for(#user) do |f| %>
<div><%= f.label :verification_code_confirmation %><br />
<%= f.number_field :verification_code_confirmation %></div>
<% end %>
User model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :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, :verification_code_confirmation, :phone
end
end
I have updated to
if #user.update_attributes(params[:user])
How do i do it? I have looked around in the internet to update my column through the verification controller but i couldn't.

Not able to update my foreign key in the new method,using Devise for Users Table

I have Two models Users and Profiles ( Users is from devise ). A user can have many profiles , so i created a migration to add user_id to Profiles.
class Profile < ActiveRecord::Base
belongs_to :user
attr_accessible :description, :name, :product, :image, :price , :user_id
mount_uploader :image, ImageUploader
validates_presence_of :name, :product,:image, :price
end
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
validates_associated :profiles
end
In my profiles controller , i have a new method to create a new profile. I want that when user logs in, he is able to see only his profiles not all.
def new
#profile = current_user.profiles.build
##profile = #user.profile.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #profile }
end
end
Ideally, my user_id column should be updated with build, but my user_id does not get updated and that is why profiles are not displayed . i am using postgresql with pg gem and when i manually add the user_id for that profile , i am able to see the profiles.
Please help to solve this, i am able to figure this out since a long time.Let me know if you want more information to solve this.
Maybe try something like this in your controller:
if current_user.profiles.count == 0
profile = Profile.create
current_user.profiles << profile
end

NoMethodError in AuthenticationsController#create | omniauth + devise

NoMethodError in AuthenticationsController#create
undefined method `user' for # /Authentication:0x00000105c7b1f8\
I'm pulling my hair out.. I downloaded the sample app from railscasts and it works.. mine has what looks like one last bug.
I am attempting to follow the railscasts to add this in to my app that is/was otherwise working -
http://railscasts.com/episodes/236-omniauth-part-2
It seems that it's mostly getting there - in the authorizations table there is a record..
I'm not getting as far as the step where the page asks for an email because it doesn't have one.
I'm sure this is super simple - here are some snippets:
controller:
class AuthenticationsController < ApplicationController
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, authentication.user)
elsif current_user
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
else
#user = User.new
#user.apply_omniauth(omniauth)
if #user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
end
end
end
devise user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
has_many :authentications
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
#attr_accessible :email, :password, :password_confirmation, :remember_me
def apply_omniauth(omniauth)
self.email = omniauth['user_info']['email'] if email.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
def password_required?
(authentications.empty? || !password.blank?) && super
end
end
some of the routes.rb:
resources :authentications
match '/auth/:provider/callback' => 'authentications#create'
get "search/show"
#devise_for :users
devise_for :users, :controllers => {:registrations => 'registrations'}
There should be #user in sign_in_and_redirect(:user, user). Not user.

Group membership error that has me pulling my hair out

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.