How to setup basic Rails models associations?












1















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 ?










share|improve this question

























  • What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

    – Mark Merritt
    Nov 25 '18 at 1:03
















1















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 ?










share|improve this question

























  • What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

    – Mark Merritt
    Nov 25 '18 at 1:03














1












1








1








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 ?










share|improve this question
















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 ?







ruby-on-rails ruby






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 10:52









Abhilash Reddy

1,1401618




1,1401618










asked Nov 24 '18 at 22:50









kevin lopezkevin lopez

336




336













  • What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

    – Mark Merritt
    Nov 25 '18 at 1:03



















  • What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

    – Mark Merritt
    Nov 25 '18 at 1:03

















What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

– Mark Merritt
Nov 25 '18 at 1:03





What do your routes look like? Are you using Rail's default RESTful routes (i.e. resources :teams in your routes.rb file? There is no need to create actions like new_team, create_team, etc. Instead, team will be implied by the name of the controller and you should simply have new, create, etc. actions.

– Mark Merritt
Nov 25 '18 at 1:03












3 Answers
3






active

oldest

votes


















1














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] } %>






share|improve this answer
























  • @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

    – kevin lopez
    Nov 24 '18 at 23:15













  • @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

    – DonPaulie
    Nov 25 '18 at 0:59



















1














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





share|improve this answer
























  • i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

    – kevin lopez
    Nov 24 '18 at 23:30











  • im going to include my controller in the code above

    – kevin lopez
    Nov 24 '18 at 23:30



















0














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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463044%2fhow-to-setup-basic-rails-models-associations%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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] } %>






    share|improve this answer
























    • @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

      – kevin lopez
      Nov 24 '18 at 23:15













    • @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

      – DonPaulie
      Nov 25 '18 at 0:59
















    1














    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] } %>






    share|improve this answer
























    • @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

      – kevin lopez
      Nov 24 '18 at 23:15













    • @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

      – DonPaulie
      Nov 25 '18 at 0:59














    1












    1








    1







    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] } %>






    share|improve this answer













    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] } %>







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 24 '18 at 23:07









    DonPaulieDonPaulie

    830923




    830923













    • @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

      – kevin lopez
      Nov 24 '18 at 23:15













    • @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

      – DonPaulie
      Nov 25 '18 at 0:59



















    • @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

      – kevin lopez
      Nov 24 '18 at 23:15













    • @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

      – DonPaulie
      Nov 25 '18 at 0:59

















    @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

    – kevin lopez
    Nov 24 '18 at 23:15







    @DonPaulid thanks for the quick reply currently when i create a team as a user the team_id column is not updating with the proper team id that it belongs to. but the record is saved in the database.

    – kevin lopez
    Nov 24 '18 at 23:15















    @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

    – DonPaulie
    Nov 25 '18 at 0:59





    @kevinlopez Try to add validates :team_id, :team, presence: true. maybe it will help you. Team_id validates presence of a number, :team validates existence of the team in the database,.

    – DonPaulie
    Nov 25 '18 at 0:59













    1














    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





    share|improve this answer
























    • i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

      – kevin lopez
      Nov 24 '18 at 23:30











    • im going to include my controller in the code above

      – kevin lopez
      Nov 24 '18 at 23:30
















    1














    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





    share|improve this answer
























    • i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

      – kevin lopez
      Nov 24 '18 at 23:30











    • im going to include my controller in the code above

      – kevin lopez
      Nov 24 '18 at 23:30














    1












    1








    1







    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





    share|improve this answer













    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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 24 '18 at 23:12









    anothermhanothermh

    3,25831531




    3,25831531













    • i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

      – kevin lopez
      Nov 24 '18 at 23:30











    • im going to include my controller in the code above

      – kevin lopez
      Nov 24 '18 at 23:30



















    • i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

      – kevin lopez
      Nov 24 '18 at 23:30











    • im going to include my controller in the code above

      – kevin lopez
      Nov 24 '18 at 23:30

















    i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

    – kevin lopez
    Nov 24 '18 at 23:30





    i have my tables made already, but when i create a team as a user that teams id is not updated on my user table, and i already added 'team_id' column

    – kevin lopez
    Nov 24 '18 at 23:30













    im going to include my controller in the code above

    – kevin lopez
    Nov 24 '18 at 23:30





    im going to include my controller in the code above

    – kevin lopez
    Nov 24 '18 at 23:30











    0














    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.






    share|improve this answer




























      0














      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.






      share|improve this answer


























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 5:42









        maxmax

        45.4k859103




        45.4k859103






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463044%2fhow-to-setup-basic-rails-models-associations%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)