[英]How to link/add models to each other
I'm trying to add idea(s)
to a user
. 我想补充idea(s)
到user
。 So far I added has_many
to my user and belongs_to
to my idea. 到目前为止,我已经将has_many
添加到我的用户,并belongs_to
我的想法。 And I added a foreign key to User using: 我使用以下命令向用户添加了外键:
rails g migration Add_User_id_To_Ideas user_id:integer
Now, how do I assign the idea to the specific user, when a user creates a new idea? 现在,当用户创建新想法时,如何将想法分配给特定用户? I tried to work parallel to this example , but I'm a bit stuck. 我尝试与此示例平行进行工作,但是有点卡住了。
user.rb user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :ideas
end
idea.rb idea.rb
class Idea < ActiveRecord::Base
belongs_to :user
has_many :comments
mount_uploader :picture, PictureUploader
# {attr_accessor :Status}
enum status: [ :Draft, :Published]
end
Several ways to do this, but I think the most straight forward way would be to save the user_id in the ideas controller create action. 有几种方法可以做到这一点,但我认为最直接的方法是将user_id保存在ideas控制器create动作中。
# def create inside ideas_controller
@idea.user_id = current_user.id
if @idea.save
# etc
Couple other options are a hidden field or before_save callback. 另外两个选项是隐藏字段或before_save回调。 Here's an example of passing through a hidden field. 这是通过隐藏字段传递的示例。 In your @idea form: 以您的@idea形式:
<%= f.hidden_field :user_id, value: current_user.id %>
This will add user_id to the params being saved. 这会将user_id添加到要保存的参数中。 Make sure that :user_id is whitelisted in the permitted params at the bottom of your ideas controller. 确保:user_id已在想法控制器底部允许的参数中列入白名单。
To permit user_id
in idea_params
: 允许在idea_params
user_id
:
def idea_params
params.require(:idea).permit(:user_id, :also_add_other_params)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.