【发布时间】:2015-03-14 13:08:17
【问题描述】:
我是新手 Grails 用户,正在 Sinatra 上试用 ActiveRecord。
基本上我想制作一个允许登录用户列出他的产品的 CRUD 应用程序。
我创建了一个用户表和一个产品表,其中用户和产品相互引用。当用户输入产品时,ActiveRecord 应该使用用户的 id 填充 Product user_id 列。
同样,用户表应该显示它拥有的所有 product_id。但我不知道如何使用 Ruby,因为它在 Grails 中是完全自动的(GORM 创建了连接表)。
这是如何在 Ruby on Sinatra 中完成的?在 Rails 下有更简单的方法吗?
我的代码如下:
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 %>">
查看产品.erb
<%=h @product.name % >
<%=h @product.quantity % >
<%=h @user.name %> ????????
迁移
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
【问题讨论】:
标签: ruby activerecord sinatra