【发布时间】:2020-06-17 01:08:45
【问题描述】:
我是 Ruby on Rails 的初学者,正在尝试在 Rails 中创建一个 Shopper 应用程序。有 3 种模型:批次、产品、用户(设计)。每个批次有很多产品,每个用户都有很多产品。我在用户和产品之间创建了一个关联(has_many)。如果我单击链接购买,如何将特定产品(每个产品都有指向产品路径的链接)添加到当前登录的用户。
我的用户模型:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
has_many :products, :dependent => :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
我的产品型号:
class Product < ApplicationRecord
belongs_to :batch
belongs_to :user
validates :name, presence: true
end
路线文件:
Rails.application.routes.draw do
devise_for :users
root to: 'batches#index'
resources "batches", only: %i[index show]
resources "products"
end
架构文件:
ActiveRecord::Schema.define(version: 2020_06_16_134907) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "batches", force: :cascade do |t|
t.string "name"
t.integer "code"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "products", force: :cascade do |t|
t.string "name"
t.bigint "batch_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.bigint "user_id"
t.index ["batch_id"], name: "index_products_on_batch_id"
t.index ["user_id"], name: "index_products_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "products", "batches"
end
产品控制器:
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
end
def index
@products = Product.order(:name)
end
def new
@product = Product.new
end
def create
@product = current_user.products.build(params[:product])
if @product.save
puts 'yes'
else
puts 'no'
end
end
private
def prod_params
params.require(:product).permit(:name, :user_id)
end
end
如果将产品添加给用户,建议我指定 redirect_to 链接。我正在打印一条消息。显然它没有打印出来。 我也提到了这个:How to associate a Devise User with another existing model?
提前致谢。
【问题讨论】:
-
您是否希望在保存产品后将其重定向到其他路径?而路径是当前用户购买的产品?
标签: ruby-on-rails ruby devise associations ruby-on-rails-6