dimanche 17 septembre 2017

Adding records to a 'has_many :through' association using a button

This is my first Rails app and have hit another wall. I have a User model and a Country model. They have a many-to-many relationship, which I join together with a Trip model.

A user can maintain a list of countries that they have been to. On the Country page, I want to have a simple bootstrap button so the current_user can add or remove the country to their list.

I am using a partial that looks like the below to at least render buttons on all the pages.

_add_remove_countries.html.erb

<% if @user.countries.exists?(@country.id) %>
    <%= form_for(@user) do |f| %>
      <%= f.submit "Remove Country", class: "btn btn-info" %>
    <% end %>
<% else %>  
    <%= form_for(@user) do |f| %>
      <%= f.submit "Add Country", class: "btn btn-info" %>
    <% end %>
<% end %>

I have tried a few different things, with no luck so I have just reverted to the basic structure. I am currently using a form_for, however that is just what has worked best so far, I am not tied to that solution.

Below are my controllers if needed, I have not set up a Trips controller as I am only using it to join the User and Country Model (maybe I need to set one up?).

users_controller.rb

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
    @countries = Country.all
  end 

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to @user
    else
      render 'new'
    end
  end

  def update
      redirect_to user_path
  end


  private 

    def user_params
        params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end


end

countries_controller.rb

class CountriesController < ApplicationController

    before_action :require_user, only: [:index, :show]

  def index
    @countries = Country.all
    @sort = CS.countries.sort_by {|key, value| value}
    @sort = @sort.first @sort.size - 2

  end

  def show
    @country = Country.find(params[:id])
    @user = User.find(session[:user_id])
  end

end

Aucun commentaire:

Enregistrer un commentaire