[英]Rails 4 devise create associated resource with 'build' not working
Im using gem 'devise', '~> 3.3.0' 我正在使用gem'devise','〜> 3.3.0'
my links_controller.rb 我的links_controller.rb
def new
@link = current_user.links.build
end
def create
@link = current_user.build(link_params)
respond_to do |format|
if @link.save
format.html { redirect_to @link, notice: 'Link was successfully created.' }
format.json { render :show, status: :created, location: @link }
else
format.html { render :new }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
private
def link_params
params.require(:link).permit(:title, :url)
end
I have add user_id to my links table. 我已经将user_id添加到我的链接表中。 And already setup the relationship in User and Link model like so:
并且已经在用户和链接模型中设置了关系,如下所示:
class Link < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :links
end
But I got this error: undefined method `build' for #. 但是我遇到了这个错误:#的未定义方法“ build”。 What do I missed?
我错过了什么?
The first line of your create
method is missing the links
association: create
方法的第一行缺少links
关联:
def create
@link = current_user.links.build(link_params)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.