[英]In my rails app, how can I automatically attach a userID when a new product is created?
I have a rails app, with two separate DB tables, users and products. 我有一个Rails应用,其中有两个单独的数据库表,用户和产品。 A user has_many products, and a product belongs_to a user. 用户有很多产品,而产品属于一个用户。
When I create a product, I want it to automatically add the user_id to the user_id database column in the products table. 创建产品时,我希望它自动将user_id添加到products表中的user_id数据库列中。 What changes to my mvc do I need to make to ensure that the correct user_id is added when a new product is created? 我需要对我的mvc进行哪些更改,以确保在创建新产品时添加正确的user_id?
You can scope the creation of the new product through the user. 您可以通过用户来限制新产品的创建。
For example, instead of this: 例如,代替此:
Product.create(params[:product])
you do this: 你做这个:
current_user.products.create(params[:product])
where "current_user" is the user creating the product. 其中“ current_user”是创建产品的用户。
Just as a suggestion, you may want to go back and accept the answers to some of your previous questions, which will improve your response rate and increase the likelihood someone will answer your questions in the future. 仅作为建议,您可能需要返回并接受一些以前的问题的答案,这将提高您的答复率,并增加将来有人回答您问题的可能性。
There are a few ways to do this, one approach: 有几种方法可以做到这一点,一种方法是:
Create current user function 创建当前用户功能
class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
# a Rails application; logging in sets the session value and
# logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by_id(session[:current_user_id])
end
end
http://guides.rubyonrails.org/action_controller_overview.html#session http://guides.rubyonrails.org/action_controller_overview.html#session
Make sure to be cognizant of security concerns. 确保意识到安全问题。 A gem like Devise can also help. 像Devise这样的宝石也可以提供帮助。
Add to products controller 添加到产品控制器
class ProductsController < ApplicationController
def create
current_user.products.create! params[:product] # make sure attr_accessible is setup on products
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.