2017-10-11 76 views
0

我對rails有個疑問。product.number for user_id rails

我有一個用戶控制器, 我有一個產品控制器。

我在產品中有一個用戶ID引用:db。

如何將User.product號碼放入Html中?

+0

把它放進hidden_​​field – Sunny

回答

0

首先,您需要爲您的用戶模型配置devise gem進行身份驗證,以將user_id列添加到您的產品表中。

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列。

爲了得到一個特定用戶的所有產品

在用戶控制顯示動作

def show 

@user_products = @user.products 

end 

的@user_products將所有屬於相應用戶的產品。