how to get user who creates role in ruby on rails - ruby-on-rails

I want to get user info like usernaem or first name who create roles in my ROR application. There are many to many association between users and roles by having role_users as join table. I am able to crate roles and save them. But i have no idea how to get user who creates role. For example,if I am Admin, I can create new roles in application. While creating role, I need to get user who is creating that role in roles_controller.rb.
roles_controller.rb
class RolesController < ApplicationController
before_filter :authorize_admin!
def index
#roles = Role.all
end
def new
#role = Role.new
end
def create
#role = Role.new(params[:role])
# #article.user_id = current_user.id
#role_user.user_id = current_user.id
if #role.save
flash[:success] = "role created!"
redirect_to roles_path(#role)
else
render 'new'
end
end
def show
#role = Role.find(params[:id])
end
def edit
#role = Role.find(params[:id])
end
def update
#role = Role.find(params[:id])
if #role.update_attributes(params[:role])
flash.notice = "Role #{#role.name} has been updated"
redirect_to role_path(#role)
else
render 'edit'
end
end
def destroy
#role = Role.find(params[:id])
#role.destroy
redirect_to action: 'index'
end
end
users_controller.rb
class Admin::UsersController < Admin::BaseController
before_filter :find_user, :only => [:show, :edit, :update, :destroy]
def index
#users = User.all( :order => :email )
#roles = Role.all
end
def show
end
def new
#user = User.new
end
def create
is_admin = params[:user].delete(:is_admin) == "1"
#user = User.new(params[:user])
#user.save
#user_role = RoleUser.new({:user_id => #user.id, :role_id => params[:role_id]})
#user_role.role_id = params[:role_id]
#user_role.save
#user.is_admin = is_admin
if #user.save
flash[:notice] = "User has been created."
redirect_to admin_users_path
else
flash[:alert] = "User has not been created."
render :action => :new
end
end
def edit
end
def update
if params[:user][:password].empty?
params[:user].delete(:password)
end
set_admin
if #user.update_attributes(params[:user])
flash[:notice] = "User has been updated."
redirect_to admin_users_path
else
flash[:alert] = "User has not been updated."
render :action => :new
end
end
def destroy
if #user == current_user
flash[:alert] = "You cannot delete yourself!"
else
#user.destroy
flash[:notice] = "User has been deleted."
end
redirect_to admin_users_path
end
private
def find_user
#user = User.find(params[:id])
end
def set_admin
is_admin = params[:user].delete(:is_admin) == "1"
#user.is_admin = true
end
end
user.rb
class User < ActiveRecord::Base
has_many :roles, through: :role_users
has_many :role_users
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :email, :password, :password_confirmation,
:remember_me, :first_name, :last_name, :is_admin, :contact_no, :birth_date,
:joining_date, :is_active, :is_hr, :is_manager, :user_code, :designation
# attr_accessible :title, :body
end
role_user.rb
class RoleUser < ActiveRecord::Base
belongs_to :user
belongs_to :role
attr_accessible :role_id, :user_id
end
role.rb
class Role < ActiveRecord::Base
attr_accessible :name
has_many :users, through: :role_users
has_many :role_users
end
ActiveRecord::Schema.define(:version => 20130601093644) do
create_table "role_users", :force => true do |t|
t.integer "role_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "is_admin"
t.string "username"
t.string "first_name"
t.string "last_name"
t.string "contact_no"
t.date "birth_date"
t.boolean "is_active"
t.date "joining_date"
t.string "avatar_url"
t.boolean "is_hr"
t.boolean "is_manager"
t.string "designation"
t.string "user_code"
t.string "user_role"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

Pass user_id as a params via the form:
#_form.html.haml
%input{:name => "user_id, :value => current_user.id, :type => "hidden"}
#controller:
creating_user = User.find(params[:role][:user_id])
But I don't think I'm following you completely. Is this what you're after?

If you want to get user object from.role just do #role.user. it will execute sql query which will join all 3 tables and return you a user

As per my understanding you need to add one more column into roles model i.e user_id. Make proper association between them like. User can have many roles and role belongs to User.
While creating a new role you need to pass the user_id also or use association for this will save you from passing explicitly user_id value.
ex:-
#current_user.roles.new(params[:new_role])
when you will role_user object you can fetch role owner data with proper association between there models i.e User, Role, RoleUser.
ex:-
#role_user.role.user

Related

How to setup basic Rails models associations?

hey guys im working on a application where a devise user sign ups and logs in, Once the user logs in they can 'create a team' or 'join a team'. I have my associations set up like this
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
validates_presence_of :phone, :city, :state, :street, :zip, presence: true, on: :create
belongs_to :team
end
team.rb
class Team < ApplicationRecord
has_many :users
end
and my tables are set up
schema.rb
create_table "teams", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "team_name"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "firstname"
t.integer "team_id"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
team_controller.rb
class TeamController < ApplicationController
before_action :authenticate_user!
def index
#team = current_user.team
end
def new_team
end
def create_team
#team = current_user.create_team(sanitize_team)
if #team.save
redirect_to team_root_path
else
render json: #team.errors.full_messages
end
end
def join_team
#teams = Team.all
end
def team
end
private
def sanitize_team
params.require(:team).permit(:team_name, :team_statement)
end
end
I want the users 'team_id' attribute to update with the teams id when they create a team. or when they join a team. Are my associations correct? how would i make this happen in the controller ?
Yes, associations are correct. You can do it better only by adding foreign key to your database schema. It can be done by generator rails g migration AddTeamToUsers team:references
More information about associations can be found here: https://guides.rubyonrails.org/association_basics.html
In controller you have to change only the whitelisting params to allow team_id. And you probably need to add to your form in view something like this:
<%= f.select :team_id, Team.all.map { |t| [t.team_name, t.id] } %>
Let's strip your code example down to the minimum required:
# app/models/team.rb
class Team < ApplicationRecord
has_many :users
end
# app/models/user.rb
class User < ApplicationRecord
belongs_to :team
end
# db/migrate/20181124230131_create_teams.rb
class CreateTeams < ActiveRecord::Migration[5.2]
def change
create_table :teams do |t|
t.string :team_name
t.timestamps
end
end
end
# db/migrate/20181124230136_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.belongs_to :team
t.timestamps
end
end
end
Then in your controller:
team = Team.where(team_name: 'foo').first_or_create!
team.users << current_user
Start by setting the association up as optional:
class User < ApplicationController
belongs_to :team, optional: true
end
Otherwise the validations on the user model will not let the user be saved without a team.
Then setup the teams resource:
# config/routes.rb
resources :teams do
post :join
end
post :join creates an additional POST /teams/:team_id/join route.
Then setup the controller:
class TeamsController
# ...
# GET /teams/new
def new
#team = Team.find
end
# POST /teams
def create
#team = Team.new(team_params)
if #team.save
unless current_user.team
current_user.update(team: #team)
end
redirect_to 'somewhere'
else
render :new
end
end
# ...
def join
#team = Team.find(params[:team_id])
if current_user.update(team: #team)
redirect_to #team, notice: 'Team joined'
else
redirect_to #team, error: 'Could not join team'
end
end
#
private
def team_params
params.require(:team).permit(:team_name, :team_statement)
end
end
Note that prefixing your action names is neither needed nor compatible with the "Rails way". Prefixing column names is also largely superfluous.

Rails - Creating a belongs_to association between models prevents me from editing the model

I'm trying to create an association between two models in my Rails app (User and Coin) where Coin belongs_to User and User has_many Coins. When I add the belongs_to association in the Coin model, I am no longer able to edit or create Coin pages. Why would it do this? As soon as I remove the association, I'm able to create/edit again. Also, the corresponding has_many association on the User page does not have the same effect. I'd appreciate any help in understanding what is happening here and how I can properly make this association. Thanks.
User.rb
class User < ApplicationRecord
acts_as_votable
has_many :questions, dependent: :destroy
has_many :events, dependent: :destroy
has_many :links, dependent: :destroy
has_many :posts, dependent: :destroy
has_many :moderated_coins, class_name: "Coin"
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, authentication_keys: [:login]
validates :username, presence: :true, uniqueness: { case_sensitive: false }
validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
validate :validate_username
def validate_username
if User.where(email: username).exists?
errors.add(:username, :invalid)
end
end
def login=(login)
#login = login
end
def login
#login || self.username || self.email
end
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
elsif conditions.has_key?(:username) || conditions.has_key?(:email)
where(conditions.to_h).first
end
end
end
Coin.rb
class Coin < ApplicationRecord
validates :currency_name, presence: true
has_many :questions, dependent: :destroy
has_many :events, dependent: :destroy
has_many :links, dependent: :destroy
mount_uploader :picture, PictureUploader
has_and_belongs_to_many :genres
# belongs_to :moderator, class_name: "User". <--- * The problem is here
validate :picture_size
private
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "Picture must be smalled than 5MB.")
end
end
end
coins_controller.rb
class CoinsController < ApplicationController
load_and_authorize_resource param_method: :question_params
before_action :find_coin, only: [:edit, :update, :destroy ]
before_action :authenticate_user!, except: [:index, :create, :show]
def index
#search = Coin.ransack(params[:q])
#coins = #search.result(distinct: true)
end
def new
#coin = Coin.new
end
def create
#coin = Coin.new(coin_params)
if #coin.save
flash[:success] = "Coin created"
redirect_to #coin
else
render 'new'
end
end
def show
#coin = Coin.find(params[:id])
end
def edit
authorize! :update, #coin
end
def update
if #coin.update(coin_params)
redirect_to #coin
else
render 'edit'
end
end
def destroy
Coin.find(params[:id]).destroy
redirect_to coins_url
end
private
def coin_params
params.require(:coin).permit( :currency_name, :currency_abbrev, :moderator_id, :accepted, :picture, :question1, :question2, :question3, :question4, genre_ids:[])
end
def find_coin
#coin = Coin.find(params[:id])
end
end
user_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
end
schema.rb
create_table "coins", force: :cascade do |t|
t.string "link_name"
t.string "currency_name"
t.string "currency_abbrev"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "permalink"
t.boolean "accepted", default: false
t.datetime "accepted_at"
t.string "genre"
t.integer "genre_id"
t.integer "moderator_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
t.string "wallet"
t.boolean "admin", default: false
t.boolean "moderator", default: false
t.decimal "currentbalance", precision: 8, scale: 2
t.decimal "payout_to_date", precision: 8, scale: 2
t.text "bio"
t.string "link1"
t.string "link2"
t.string "link3"
t.string "link4"
t.string "link5"
t.string "name"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
Use:
belongs_to :moderator, class_name: "User", optional: true
In rails 5, belongs_to enforces existence of the associated record by default. You need to use optional: true in order to allow moderator_id to be nil.

How to fill multiple form fields using attribute from another model?

I have 3 models - User, Shipment and Friendship. User can be friends with another user via Friendship-model. User also can create Shipments and can add a Friend-User to it. There is address-attribute in User and Shipment models. I need to give User a possibility to fill that address field in 2 ways at the same form:
By filling the address field manually.
By choosing from select-list a Friend of that User - so the Friends
address-attribute transfers and fills the Shipments adress-attribute
(like ctrl-c/ctrl-v) and User can Submit the form.
I can guess, that AJAX is needed to refresh the content without refreshing the page.
Shipment model:
class Shipment < ActiveRecord::Base
belongs_to :user
belongs_to :friendship
validates :image, presence: true
validates :user_id, presence: true
end
Shipments controller:
class ShipmentsController < ApplicationController
helper_method :shipment, :user
before_action :set_shipment, only: [:show]
before_action :authenticate_user!
before_action :require_same_user, only: [:show]
def index
#shipments = Shipment.all
end
def new
#shipment = Shipment.new
end
def create
#shipment = Shipment.new(shipment_params)
#shipment.user = current_user
if #shipment.save
flash[:success] = "Shipment etc."
redirect_to shipment_path(#shipment)
else
render 'new'
end
end
def show
#shipment = Shipment.find(params[:id])
end
private
def user
#user = current_user
end
def shipment
#shipment = user.shipments.new
end
def shipment_params
params.require(:shipment).permit(:name, :kg, :length, :width, :height,
:adress, :image, :user_id, :friend_id)
end
def set_shipment
#shipment = Shipment.find(params[:id])
end
def require_same_user
if current_user != #shipment.user
flash[:alert] = "Restricted/"
redirect_to root_path
end
end
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
has_many :shipments, dependent: :destroy
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, :class_name => 'Friendship',
:foreign_key => 'friend_id'
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end
Users controller (the User itself is created by Devise)
class UsersController < ApplicationController
before_action :authenticate_user!
def show
#user = User.find(params[:id])
end
def my_friends
#friendships = current_user.friends
end
def search
#users = User.search(params[:search_param])
if #users
#users = current_user.except_current_user(#users)
render partial: 'friends/lookup'
else
render status: :not_found, nothing: true
end
end
private
def require_same_user
if current_user != set_user
flash[:alert] = "Restricted."
redirect_to root_path
end
end
def set_user
#user = User.find(params[:id])
end
end
Friendship model:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User'
has_many :shipments
end
Friendships controller:
class FriendshipsController < ApplicationController
def index
#friendships = Friendship.all
end
def create
#friendship = current_user.friendships.build(:friend_id => params[:friend_id])
if #friendship.save
flash[:success] = "Added to friends."
redirect_to my_friends_path
else
flash[:alert] = "Impossible to add as a friend."
redirect_to my_friends_path
end
end
def destroy
#friendship = current_user.friendships.find_by(friend_id: params[:id])
#friendship.destroy
flash[:notice] = "Unfriended."
redirect_to my_friends_path
end
private
def name
#name = friend_id.name
end
end
Schema:
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "shipments", force: :cascade do |t|
t.string "name"
t.integer "length"
t.integer "width"
t.text "adress"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.integer "height"
t.integer "kg"
end
add_index "shipments", ["user_id"], name: "index_shipments_on_user_id"
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.integer "phone", limit: 30
t.string "username"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
Shipment form view (new):
<%= form_for(shipment, html: { multipart: true }) do |f| %>
<p>Choose a friend from your friendlist or fill the address field manually:</p>
<%= f.select :friend_id, user.friendships.map{ |friendship|
[friendship.friend.name, friendship.id] } %>
<%= f.text_field :adress, placeholder: "Address and index" %>
<%= f.submit "Submit", class: "button" %>
<% end %>
With ActiveRecord::Base, you could use eager loading and nested form to solve your problem.
Eager load the object related to the main object and use nested form to display the related object.

Adding user_ids to each article(devise)

I have a user model:
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
has_secure_password
has_many :articles
And my schema for User looks like:
create_table "users", force: true do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
end
Half of these are from the devise gem. So what I'm trying to accomplish is having each article have an author assigned to it(first_name + last_name).
My article model looks like:
belongs_to :topic
belongs_to :user
def author
"#{self.user_id.first_name} #{self.user_id.last_name}"
end
And my actions in the article controller looks like:
def create
#article = Article.new(article_params)
#article.user = current_user
if #article.save
##article.user = session[:user_id]
flash[:notice] = "Article has been uploaded"
redirect_to(:action => "show", :id => #article.id)
else
flash[:notice] = "Please fill in all fields."
render("new")
end
end
And if I do <p><%=#article.author%></p> in my show view, it has an error that says undefined method - 'first_name'
How do I add authors to each article.
Use self.user.first_name instead of self.user_id.first_name.in your author method
And #article.user = current_user is fine if you want ot use user_id in this case then
use #artilce.user_id = current_user.id
okay here is how you do it:
user.rb
has_many :items
article.rb
belongs_to :user
articles_controller.rb
def create
#article = Article.new(params[:article].permit(:name, ...))
#article.user_id = current_user.id
if #article.save
flash[:notice] = 'article created'
redirect_to #article
else
render 'new'
end
end

Rails (One Month Rails) NoMethodError in PinsController#create - can't add new pin

When I try to add a new pin, I can't. Instead, I get this error:
NoMethodError in PinsController#create
undefined method `name' for #<pin:0x000001011b9638>
Application Trace | Framework Trace | Full Trace
app/controllers/pins_controller.rb:48:in `block in create'
app/controllers/pins_controller.rb:47:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"n9E2nob/KBzu20PEzYoQWXnibAUR5TH6iPWNd66383k=",
"pin"=>{"description"=>"stea"},
"commit"=>"Create Pin"}
pins_controller.rb
def create
#pin = current_user.pins.new(params[:pin])
respond_to do |format|
if #pin.save
format.html { redirect_to #pin, notice: 'Pin was successfully created.' }
format.json { render json: #pin, status: :created, location: #pin }
else
format.html { render action: "new" }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
app/model/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :name
has_many :pins, :dependent => :destroy
end
routes.rb
Omrails::Application.routes.draw do
resources :pins
devise_for :users
root :to => 'pages#home'
get 'about' => 'pages#about'
app/models/pin.rb
class Pin < ActiveRecord::Base
attr_accessible :description
validates :description, presence: true
validates :name, presence: true
belongs_to :user
validates :user_id, presence: true
end
db/migrate/create_pins
class CreatePins < ActiveRecord::Migration
def change
create_table :pins do |t|
t.string :description
t.timestamps
end
end
end
db/migrate/add_user_id_to_pins.rb
class AddUserIdToPins < ActiveRecord::Migration
def change
add_column :pins, :user_id, :integer
add_index :pins, :user_id
end
end
db/migrate/add_name_to_users.rb
class AddNameToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
end
end
Any ideas about what has gone wrong?
Not sure if it's relevant, but this used to work. I was able to follow along Mattan Griffel's One Month Rails course -- Add Assoc bt Pins and Users video until 29m50s but then I realized that I had to skip back to Customizing Devise bec I forgot to add simple forms.
Now that simple forms have been added, I am trying to go forward - and getting stuck here :(
UPDATE: I ran migrate redo for creating pins and adding user id to pins. Then I removed the validate name line. Now I get the following error when I create pin
ActiveRecord::UnknownAttributeError in PinsController#new
unknown attribute: user_id
app/controllers/pins_controller.rb:29:in `new'
pins_controller.rb
def new
#pin = current_user.pins.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #pin }
end
end
Many thanks for helping
db/schema.rb
ActiveRecord::Schema.define(:version => 20130828163738) do
create_table "pins", :force => true do |t|
t.string "description"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
You are validating the presence of :name in the Pin model but it does not have a :name field. Your User has.
Just remove the validates :name, presence: true from you Pin model (line 5).
What happened is that Rails, when trying to save your Pin model, will run all the validations. When it encounters the presence validation on :name, it will check to see if #pin.name isn't blank. But the thing is that your Pin model does not have a name method. So it raises this error.
If you actually want your Pin model to have a name, add it the to pins table:
$ rails g migration add_name_to_pins name:string
$ rake db:migrate

Resources