0
私にはレールに関する質問があります。product.number for user_id rails
私はユーザーコントローラを持っています。 私はProductコントローラを持っています。
私はproduct:dbにユーザーIDリファレンスがあります。
User.product numberをHtmlに配置する方法は?
私にはレールに関する質問があります。product.number for user_id rails
私はユーザーコントローラを持っています。 私はProductコントローラを持っています。
私はproduct:dbにユーザーIDリファレンスがあります。
User.product numberをHtmlに配置する方法は?
まず、user_idカラムを商品テーブルに追加するために、ユーザモデルへの認証用にdevise gemを設定する必要があります。ユーザーおよび製品として
rails g migartion add_user_id_to_products user_id:integer:index
ユーザーモデルでは
class User < ApplicationRecord
has_many :products
end
貴社の製品モデルで
class Products < ApplicationRecord
belongs_to :user
end
にhas_manyとbelongs_toの通過関連しています。 あなたは以下のようにデータが正常にデータベースに保存されている場合は製品コントローラ
class ProductsController < ApplicationController
def index
@products = Product.all
end
def new
@product = Product.new
end
def create
@product = current_user.products.build(product_params)
if @product.save
redirect_to edit_product_path(@product), notice: "Saved..."
else
render :new
end
end
private
def product_params
params.require(:product).permit(:title, :description, :category)
end
end
で、あなたはCURRENT_USERのIDで満たされた製品テーブルのUSER_ID列を見つけることができます。 @user_productsは、該当するユーザーに属するすべての製品を持つことになります
def show
@user_products = @user.products
end
ユーザーコントローラのshowアクションでは、特定のユーザー
のすべての製品を取得するには
。
hidden_fieldに入れる – Sunny