【问题标题】:ActiveRecord on Sinatra basic associations and IDsSinatra 基本关联和 ID 上的 ActiveRecord
【发布时间】: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


    【解决方案1】:

    迁移中的 add_reference 部分将 user_id 添加到产品中

    在应用程序中:

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

    在视图中:

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

    【讨论】:

    • 谢谢,我用 add_reference(:products, :user) 替换了 t.references: user 并且它起作用了。我也不知道.merge。 add_references 和 t.references 有什么区别?
    猜你喜欢
    • 1970-01-01
    • 2016-01-14
    • 2015-06-23
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多