I am building a rails site that is has gyms and reviews. I would like users to be able to leave reviews for gyms. I have my tables set up as
class Gym < ActiveRecord::Base
has_many :pictures, as: :imageable
has_many :reviews
end
and
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :gym
validates :body, presence: true, length: { maximum: 1000 }
validates :rating, presence: true
end
Right now the gym controller is static (can't CRUD gyms, as that's an admin thing) and just renders the pages w/ info. I am trying to add reviews, but I don't want to muddle associations. Here is my gym controller info
class GymsController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
def index
@q = Gym.ransack(params[:q])
@gyms = @q.result
@other_gyms = Gym.all
if @gyms.to_a.count < 1
flash[:warning] = "No gym matched #{params[:q][:name_or_phone_number_or_city_or_zip_code_cont]}"
end
end
def new
@gym = Gym.find(params[:id])
@review = @gym.review.new
end
def create
@gym = Gym.find(params[:id])
@review = @gym.reviews.build(gym_params)
if @review.save
flash[:success] = 'Review Saved'
redirect_to :back
else
render 'new'
end
end
def show
@gym = Gym.find(params[:id])
@reviews = @gym.reviews
end
private
def gym_params
params.require(:gym).permit(:name, :description, :address, :address_2, :zip_code,
:phone_number, :website_url, :city, :state, :latitude, :longitude,
review_attributes: [:user_id, :rating, :body, :gym_id])
end
def logged_in_user
unless logged_in?
store_location
flash[:danger] = 'Please log in'
redirect_to login_url
end
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
end
my routes
resources :gyms, only: [:index, :show] do
resources :reviews
end
and the gym/show link_to which points to gyms/:id/reviews
In gyms/new I have the review form
<%= form_for [@gym, @review] do |f| %>
<%= f.label :rating, 'Select your rating' %>
<div id='ratyRating'></div><br>
<%= f.text_area :body, size: '100x10' %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.submit 'Post', class: 'btn btn-gen' %>
<% end %>
this does not work. and from the link_to button I get it directing to gyms/:id/reviews which is an index page. I feel like there is a much better way to do this. Does anyone see what I am doing wrong here?
correct_userfilter gets the user id fromparams[:id].flash[:warning] = "No gym matched #{params[:q][:name_or_phone_number_or_city_or_zip_code_cont]}"exposes your users to an injection vulnerability since you are echoing back the params.