【发布时间】:2018-12-11 23:37:29
【问题描述】:
更新 2
到目前为止,我所做的是 rails generate migration add_user_reference_to_products
然后我做了
类 AddUserReferenceToProducts
但我正在获取 PG::DuplicateColumn: ERROR: 关系“request_items”的列“user_id”已经存在。
当我在视图中引用它(作为@products.user_id)时,它是空白的。我尝试过创建一个新产品,但它不起作用。我应该做什么,因为我现在做不到,为了我现在的生活,弄清楚现在该做什么。
更新
我想做类似@products.users.username 的操作(如果有其他方法,请告诉我)为他们创建的产品显示用户的用户名。
目前,我没有修改如下所述的代码,但如果需要更多信息,请告诉我。另外,如果您能够提供分步流程,我将不胜感激。
克莱德提供的答案对我不起作用(未定义的方法“用户名”)。
问题:尽管已经在模型中定义了这种关系,但我如何才能将用户控制器与产品控制器链接? (一个用户可以创建多个产品,一个产品属于一个用户)
我有一个网站,用户可以在其中创建产品。现在,这些用户也有一个个人资料页面。我想知道是否可以拥有它,所以当用户创建产品并单击产品本身时,它会显示哪个用户创建了它,当我单击用户名时,它会指向他们的个人资料页面。
目前,唯一不工作的是用户名没有出现在他们创建的产品上,路线和其他一切都在工作。
对于用户,相关代码:
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@users = User.find(params[:id])
end
end
架构
create_table "users", force: :cascade do |t|
t.string "email"
t.string "username"
t.string "encrypted_password"
t.string "description"
t.string "address"
t.string "phone_number"
end
对于产品:
class ProductsController < ApplicationController
def index
@products = Product.all
end
def new
@products = Product.new
end
def create
params[:products][:user_id] = current_user.id
@products = products.new(products_params)
end
def edit
@products = Product.find(params[:id])
end
def update
@products = Products.find(params[:id])
@products.update_attributes!(products_params)
flash[:notice] = "#{@products.name} has been succesfully updated."
redirect_to show_my_products_path
end
def destroy
@products = Product.find(params[:id])
@products.destroy
flash[:notice] = "Your product '#{@products.name}' has been deleted."
redirect_to show_my_products_path
end
def show
@products = Product.find(params[:id])
end
end
架构
create_table "products", force: :cascade do |t|
t.string "name", default: "", null: false
t.string "description"
t.string "quantity"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
对于展示产品页面,它本质上是显示产品信息。我想添加的一件事是这一行:
<%= link_to "#{user.username}", users_show_path_url(user), class: 'link_to' %>
如果您单击用户创建的产品页面上的此链接,它将定向到他们的个人资料页面。但是,在产品的 show.html.erb 页面中,我确实收到了错误:
undefined method `username' for nil:NilClass
或
Couldn't find User with 'id'= ....
我想,我不太确定如何链接创建他们产品的用户并在该特定产品上显示他们的用户名。我试过添加:
@users = User.all
@users = User.find(params[:id])
致展会产品负责人。
另外,这是模型:
class User < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :user
end
我故意省略了一些代码并选择了最相关的代码,但如果您需要更多代码,请告诉我。
我想要的是当有人点击该产品时,他们可以看到是哪个用户创建了它,并看到他们的用户名,因此点击该用户名即可转到用户个人资料。产品和用户之间的唯一链接是产品表中的“user_id”。因此,当创建产品时,user_id 与该项目相关联。
【问题讨论】:
标签: ruby-on-rails