Multi model sign up with clearance in Rails 4 - ruby

So I want to create a Company while signing up as a new user to my application. I use https://github.com/thoughtbot/clearance for authentication.
I have these 2 migrations:
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name, null: false
t.string :email, null: false
t.attachment :logo
t.timestamps null: false
end
end
end
And
class CreateClearanceUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email, null: false
t.string :encrypted_password, limit: 128, null: false
t.string :confirmation_token, limit: 128
t.string :remember_token, limit: 128, null: false
t.string :first_name
t.string :last_name
t.attachment :avatar
t.integer :company_id
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :remember_token
end
end
My models look like this:
class User < ActiveRecord::Base
include Clearance::User
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users
end
This is my altered Clearance controller:
class Clearance::UsersController < ApplicationController
before_filter :redirect_signed_in_users, only: [:create, :new]
skip_before_filter :require_login, only: [:create, :new]
skip_before_filter :authorize, only: [:create, :new]
def new
#user = User.new
#user.build_company
render template: "users/new"
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
redirect_back_or url_after_create
else
render template: "users/new"
end
end
private
def avoid_sign_in
warn "[DEPRECATION] Clearance's `avoid_sign_in` before_filter is " +
"deprecated. Use `redirect_signed_in_users` instead. " +
"Be sure to update any instances of `skip_before_filter :avoid_sign_in`" +
" or `skip_before_action :avoid_sign_in` as well"
redirect_signed_in_users
end
def redirect_signed_in_users
if signed_in?
redirect_to Clearance.configuration.redirect_url
end
end
def url_after_create
Clearance.configuration.redirect_url
end
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, companies_attributes: [:id, :name])
end
end
And at last my form:
<div class="form-item">
<%= form.label :first_name %>
<%= form.text_field :first_name, type: "text" %>
</div>
<div class="form-item">
<%= form.label :last_name %>
<%= form.text_field :last_name, type: "text" %>
</div>
<div class="form-item">
<%= form.label :email %>
<%= form.text_field :email, type: "email" %>
</div>
<div class="form-item">
<%= form.fields_for :companies do |builder| %>
<label>Company</label>
<%= builder.text_field :name, type: "text" %>
<%end%>
</div>
<div class="form-item">
<%= form.label :password %>
<%= form.password_field :password %>
</div>
I can perfectly submit my form, but my company_id is nil when finding the user object in rails console.
Anyone have an idea what I am doing wrong?
Thanks in advance!

You need to use the singular:
= form.fields_for :company
and in your controller:
company_attributes # instead of companies_attributes
and you have one thing in the wrong model! You want to save a company with the user so you need to move accepts_nested_attributes_for to user.rb
accepts_nested_attributes_for :company

Related

Error: Validation failed: Images imageable must exist , rails-5.0 , paperclip-5

While i was trying to submit the form, following error occured: Validation failed: Images imageable must exist and render the same new.html.erb view.
If i comment the file field in new.html.erb. Product is being created successfully.
ProductsController:
def new
#product = Product.new
end
def create
#product = Product.create!(product_params)
if #product.save
redirect_to products_path, notice: "Product Created Successfully"
else
render "new"
end
end
def product_params
params.require(:product).permit(:name, :quantity, :price, images_attributes: [:id, :photo, :_destroy])
end
new.html.erb:
<%= nested_form_for #product, html: { multipart: true } do |f|%>
<h2>New</h2>
<P> <%= f.label :name %> <%= f.text_field :name %> </P>
<P> <%= f.label :quantity %> <%= f.text_field :quantity %> </P>
<P> <%= f.label :price %> <%= f.text_field :price %> </P>
<%= f.fields_for :images do |p| %>
<p> <%= p.label :photo %> <%= p.file_field :photo %> </p>
<%= p.link_to_remove "Remove Image" %>
<% end %>
<%= f.link_to_add "Add Image", :images %>
<%= f.submit "Add Product" %>
<% end %>
20160725102038_add_image_columns_to_imageable.rb:
class AddImageColumnsToImageable < ActiveRecord::Migration[5.0]
def up
add_attachment :images, :photo
end
def down
remove_attachment :images, :photo
end
end
Model:product.rb
class Product < ApplicationRecord
has_one :variant
has_many :images, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :images, allow_destroy: true
end
Model:image.rb
class Image < ApplicationRecord
belongs_to :imageable, polymorphic: true
has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end
In rails 5, belongs_to makes sure that the associated model must exist.
E.g In this polymorphic association, Image model has belongs_to :imageable and Product model has has_many :images.
So here in new.html.erb we are creating an image, but respective product not exist, so that's why error Image imageable must exist .
Solution
Add optional: true while making an association of belong_to in Image model.
Image Model now looks like:
class Image < ApplicationRecord
belongs_to :imageable, polymorphic: true, optional: true
has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end

has_many :through rails

I want to get user1 to accept requests from other users to join user1s post as contributors and be listed out if user1 accepts them
Can't seem to get it to work - Here's my setup:
has_many :through
I'm thinking:
post model
class Post < ActiveRecord::Base
#Join table associations
has_many :group_requests, class_name: "Group",
foreign_key: "requester_id",
dependent: :destroy
has_many :group_users, class_name: "Group",
foreign_key: "accepted_id",
dependent: :destroy
has_many :requester, through: :group_requests
has_many :accepted, through: :group_users
def request(other_post)
group_requests.create(accepted_id: other_post.id)
end
# Unfollows a user.
def unrequest(other_post)
group_requests.find_by(accepted_id: other_post.id).destroy
end
# Returns true if the current user is following the other user.
def accepted?(other_post)
requesting.include?(other_post)
end
user model
class User < ActiveRecord::Base
#Join table associations
belongs_to :group
group model
class Group < ActiveRecord::Base
belongs_to :requester, class_name: "Post"
belongs_to :accepted, class_name: "Post"
validates :requester_id, presence: true
validates :accepted_id, presence: true
end
CreatePosts Migration
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :content
t.timestamps null: false
end
end
end
DeviseCreateUsers Migration
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.integer :post_id
t.string :email, null: false, default: ""
AddUserIdToPosts
class AddUserIdToPosts < ActiveRecord::Migration
def change
add_column :posts, :user_id, :integer
add_index :posts, :user_id
end
end
CreateGroup Migration
class CreateGroups < ActiveRecord::Migration
def change
create_table :groups do |t|
t.integer :requester_id
t.integer :accepted_id
t.timestamps null: false
end
add_index :groups, :requester_id
add_index :groups, :accepted_id
add_index :groups, [:requester_id, :accepted_id], unique: true
end
end
Post Controller
def accepted
#title = "Accepted"
#post = Post.find(params[:id])
#users = #user.accepted.paginate(page: params[:page])
render 'show_accepted'
end
def requester
#title = "Requesters"
#post = Post.find(params[:id])
#users = #user.requester.paginate(page: params[:page])
render 'show_requester'
end
private
def post_params
params.require(:post).permit(:title, :content, :image)
end
Post Show
<% #post ||= current_user(#post) %>
<div class="stats">
<a href="<%= accepted_post_path(#post) %>">
<strong id="following" class="stat">
<%= #post.accepted.count %>
</strong>
following
</a>
<a href="<%= requester_post_path(#post) %>">
<strong id="followers" class="stat">
<%= #post.requester.count %>
</strong>
followers
</a>
</div>
Any suggestions?
You could try this ---
as i think p is your post and you want to get all user_ids.
p.group_members.map{|gm|gm.user_id} #list of all ids in array
### OR try this
p.users #list of all users in array
#if you want to collect ids then
p.users.collect(&:id)
I think it should be helpful for you

Displaying Current User in view through a polymorphic association

I am attempting to display the current users name once they are logged in.
Therefore at the top of the page it would say "Logged in as Patrick". However I have a polymorphic association set up whereby every user that signs up is either a player or a coach.
The polymorphic association is under the label or :tennis_player as both coach and player play tennis.
The code for the view is below.
<div class="container">
<header>
<div class="logo">
<%= link_to(image_tag 'tennis_ball.png', :width => 100, :height => 100) %>
</div>
<div class="slogan">
<h3>Setfortennis</h3>
</div>
<div id="user_nav">
<% if current_user? %>
Logged in as <%= #current_user %>
<%= link_to "log out", log_out_path %>
<% else %>
<%= link_to "Sign Up", sign_up_path %> or
<%= link_to "Log in", log_in_path %>
<% end %>
</div>
</header>
</div>
Here is my application controller
helper_method :current_user?
before_filter :get_user
def current_user?
!!current_user
end
def current_user
#current_user ||= session[:user_id] &&
User.find_by_id(session[:user_id])
end
def check_logged_in
redirect_to( new_session_path, :notice => "You must be logged in to do that!") unless current_user?
end
def get_user
#user = User.new
end
end
And here are my models. Anything else needed to solve let me know!
class Player < ActiveRecord::Base
attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :racket, :ranking, :image
has_attached_file :image, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
has_many :videos
has_one :user, :as => :tennis_player
end
class Coach < ActiveRecord::Base
attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :ranking
has_one :user, :as => :tennis_player
end
User Model.
class User < ActiveRecord::Base
attr_accessible :email, :password_hash, :password_salt, :password, :password_confirmation
attr_accessor :password
belongs_to :tennis_player, :polymorphic => true
before_save :encrypt_password
validates_confirmation_of :password
validates_confirmation_of :password, :on => :create
validates_confirmation_of :email
validates_uniqueness_of :password
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
You just need to store the right id whenever you create a session. But I would change the design a little. Instead of having two separate tables for Player and Coach, you can create a base class User, and inherit from it.
class User < ActiveRecord::Base
attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :ranking
end
class Player < User
end
class Coach < User
end

Undefined Method in Picture Controller

Warning, I'm a newb and trying to learn RoR on my own. Been doing the tutorials etc and now trying to learn through experience. Long story short I'm trying to attach a user picture from a url defined by them, with a default pic if they don't supply one. Been running into all kinds of errors, I think I have it down to one primary issue now after hours of trying to figure it all out (since I'm new at this). So right now the error I'm getting is:
NoMethodError in GravsController#update
undefined method `update_attributes' for nil:NilClass
I know this means I need to do something like:
#something = Model.new/build(params[:method])
But I don't know where to define it in my controller (I'm guessing the gravs_controller right?) So here's my code, tear it apart and see if you can help me get this image function working, please :)
class GravsController < ApplicationController
before_filter :signed_in_user
gravs_controller
def create
#graver = current_user.gravs.new(params[:content])
#grav_bool = false
if #graver.save
#grav_bool = true
#grav_bool.save
flash[:success] = "User Picture Saved!"
redirect_to faq_path
else
#grav_bool = false
#grav_bool.save
redirect_to faq_path
end
end
def update
if #graver.update_attributes(params[:content])
#grav_bool = true
#grav_bool.save
flash[:success] = "User Picture Saved!"
redirect_to faq_path
else
#grav_bool = false
#grav_bool.save
redirect_to faq_path
end
end
end
users_controller
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update, :destroy, :gravs]
before_filter :correct_user, only: [:edit, :update, :gravs]
before_filter :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
end
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to Inception!"
redirect_to gravs_path
else
render 'new'
end
end
def edit
end
def update
if #user.update_attributes(params[:user])
sign_in #user
flash[:success] = "Profile updated"
redirect_to gravsid_path
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted"
redirect_to users_path
end
private
def correct_user
#user = User.find(params[:id])
redirect_to (root_path), error: "Cannot edit others information!" unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
create.html.erb (Inside /views/gravs/)
<% provide(:title, "Edit Picture") %>
<div class="barney">
<div class="trouble">
<h1>Update Your Picture</h1>
<%= gravs_display #graver %>
<%= form_for(:grav) do |f| %>
<div class="field">
<%= f.text_field :content, placeholder: "Enter Picture URL" %>
</div>
<%= f.submit "Update User Image", class: "btn btn-small btn-primary" %>
<% end %>
</div>
</div>
update.html.erb (inside /views/gravs/)
<% provide(:title, "Edit Picture") %>
<div class="barney">
<div class="trouble">
<div class="row">
<div class="span6 offset3">
<h1>Update Your Picture</h1>
<%= gravs_display #graver %>
<%= form_for(:gravs) do |f| %>
<div class="field">
<%= f.text_field :content, placeholder: "Update Picture URL" %>
</div>
<%= f.submit "Update User Image", class: "btn btn-small btn-primary" %>
<% end %>
</div>
</div>
</div>
</div>
** datenumber_create_gravs.rb**
class CreateGravs < ActiveRecord::Migration
def change
create_table :gravs do |t|
t.string :content
t.integer :user_id
end
end
end
schema.rb
ActiveRecord::Schema.define(:version => 20130407202835) do
create_table "gravs", :force => true do |t|
t.string "content"
t.integer "user_id"
end
create_table "microposts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "microposts", ["user_id", "created_at"], :name => "index_microposts_on_user_id_and_created_at"
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "password_digest"
t.string "remember_token"
t.boolean "admin", :default => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["remember_token"], :name => "index_users_on_remember_token"
end
routes.rb
MydeaSample::Application.routes.draw do
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
root to: "static_pages#home"
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/message', to: 'static_pages#message'
match '/faq', to: 'static_pages#faq'
match '/gravs', to: 'gravs#create'
match '/gravsid', to: 'gravs#update'

Nested Form Doesn't Save Nested Model Rails 3

I am trying to create a form that creates a game and game_players at the same time.
The problem I am having is that when I submit the form, the game is created, but the game_players are not.
I've looked around, but haven't found any helpful answers.
Game Model
class Game < ActiveRecord::Base
belongs_to :league
has_many :game_players, :dependent => :destroy
accepts_nested_attributes_for :game_players
attr_accessible :league_id, :game_date
validate :league_id, :presence => true
end
Game_Player Model
class GamePlayer < ActiveRecord::Base
belongs_to :game
has_many :users
validate :game_id, :presence => true
validate :user_id, :presence => true
end
Game Controller
class GamesController < ApplicationController
def new
#title = "New Game"
#game = Game.new
3.times { #game.game_players.build }
end
def create
#game = Game.new(:league_id => cookies[:league_id])
if #game.save
flash[:success] = "Succesfully Created Game"
redirect_to League.find_by_id(cookies[:league_id])
else
#title = "New Game"
render 'new'
end
end
Form
<%= form_for #game do |f| %>
<%= f.fields_for :game_players do |builder| %>
<p>
<%= builder.label :user_id, "User" %><br />
<%= builder.text_field :user_id %><br />
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
most likely you need to pass :game_players_attributes to attr_accessible since .new respect mass-assignment security

Resources