SORA
SORA

Reputation: 77

ActiveRecord on Sinatra basic associations and IDs

I'm newbie Grails user trying out ActiveRecord on Sinatra.

Basically I want to make a CRUD app that allows a logged-in user to list down his products.

I made a Users table and a Products table, with Users and Products referencing each other. When a user enters a product, ActiveRecord is supposed to populate the Product user_id column with the User's id.

Likewise, the User's table is supposed to show all the product_ids it has. But I don't know how to do this is Ruby because it was all automatic in Grails (The GORM created the Join Table).

How is this done in Ruby on Sinatra? Is there an easier way to do it under Rails?

My code is below:

app.rb

class User < ActiveRecord::Base  
  has_many :products  

class Product < ActiveRecord::Base  
  belongs_to :user  

get "/createproduct" do  
  if current_user  
  @product = Product.new  
  erb :"createproduct"  
else  
  redirect("/login")  

post "/products" do  
@product = Product.new(params[:product])  How to make user.id or name enter the params???  
  if @product.save  
    redirect "products/#{@product.id}"  
  else  
    redirect "/createproduct"  

get "/products/:id" do  
  @product = product.find(params[:id])  
  erb :"viewproduct"  

createproduct.erb

<input name="product[name]" value="<%= @product.name %>" style="width=90%">
<input name="product[quantity]" value="<%= @product.quantity %>">

viewproduct.erb

<%=h @product.name %  >
<%=h @product.quantity %  >
<%=h @user.name %>  ????????  

migrations

class CreateProducts < ActiveRecord::Migration  
def change  
create_table :products do |t|  
 t.references :user  
 t.string :name  
 t.integer :quantity  

class CreateUsers < ActiveRecord::Migration  
def change  
create_table :users do |t|  
  t.references :product  
  t.string :name  
  t.string :password_digest  

Upvotes: 0

Views: 537

Answers (1)

Norly Canarias
Norly Canarias

Reputation: 1736

the add_reference part in your migration adds a user_id into the product

in the app:

post "/products" do  
  @product = Product.new(params[:product].merge(user_id: current_user.id))
  if @product.save  
    redirect "products/#{@product.id}"  
  else  
    redirect "/createproduct" 

in the view:

<%=h @product.name %>
<%=h @product.quantity %>
<%=h @product.user.name %> 

Upvotes: 0

Related Questions