Create rails record from two ids
Posted
by
Michael Luby
on Stack Overflow
See other posts from Stack Overflow
or by Michael Luby
Published on 2012-12-01T05:02:22Z
Indexed on
2012/12/01
5:03 UTC
Read the original article
Hit count: 110
ruby-on-rails
|activerecord
The functionality I'm trying to build allows Users to Visit a Restaurant.
I have Users, Locations, and Restaurants models. Locations have many Restaurants.
I've created a Visits model with user_id and restaurant_id attributes, and a visits_controller with create and destroy methods.
Thing is, I can't create an actual Visit record. Any thoughts on how I can accomplish this? Or am I going about it the wrong way.
Here's the code:
Model:
class Visit < ActiveRecord::Base
attr_accessible :restaurant_id, :user_id
belongs_to :user
belongs_to :restaurant
end
View:
<% @restaurants.each do |restaurant| %>
<%= link_to 'Visit', location_restaurant_visits_path(current_user.id, restaurant.id), method: :create %>
<% @visit = Visit.find_by_user_id_and_restaurant_id(current_user.id, restaurant.id) %>
<%= @visit != nil ? "true" : "false" %>
<% end %>
Controller:
class VisitsController < ApplicationController
before_filter :find_restaurant
before_filter :find_user
def create
@visit = Visit.create(params[:user_id => @user.id, :restaurant_id => @restaurant.id])
respond_to do |format|
if @visit.save
format.html { redirect_to location_restaurants_path(@location), notice: 'Visit created.' }
format.json { render json: @visit, status: :created, location: @visit }
else
format.html { render action: "new" }
format.json { render json: @visit.errors, status: :unprocessable_entity }
end
end
end
def destroy
@visit = Visit.find(params[:user_id => @user.id, :restaurant_id => @restaurant.id])
@restaurant.destroy
respond_to do |format|
format.html { redirect_to location_restaurants_path(@restaurant.location_id), notice: 'Unvisited.' }
format.json { head :no_content }
end
end
private
def find_restaurant
@restaurant = Restaurant.find(params[:restaurant_id])
end
def find_user
@user = current_user
end
end
© Stack Overflow or respective owner