[英]Can't access id of a model after saving?
I'm trying to link to a nested model, however, the id seems to be nonexistent. 我正在尝试链接到嵌套模型,但是,该ID似乎不存在。
In this form, I have the following 以这种形式,我有以下内容
<% @photos.persons.each do |ans| %>
<div class="container">
<div class="row-fluid">
</p>
<p>
<%= ans.text %>
</p>
<h5><em>
<%= ans.commenter %> posted
<%= link_to "Persons", photo_person_path(photos_id: @photo.id, id: ans.id) %>
</em></h5>
</div>
</div>
<% end %>
However, it seems ans has no id? 但是,似乎ans没有id? I have created the model via a form_for but cannot access its id. 我已经通过form_for创建了模型,但是无法访问其ID。 this is my create action for persons 这是我为人创造的行动
def create
@person = @photo.persons.new(params[:person])
if @person.anonymous == true
@person.commenter = "Anonymous"
else
@person.commenter = current_user.username
end
if @person.save
redirect_to photo(@photo)
else
redirect_to photos
end
end
Any ideas? 有任何想法吗?
1. "Persons" 1.“人”
Although Rails will naturally pluralize person
as people
, what have you got your association set up as? 虽然Rails会自然变复数person
作为people
,你有你的协会成立为?
You should have this: 你应该有这个:
#app/models/photo.rb
Class Photo < ActiveRecord::Base
has_many :persons, class_name: "Person"
end
2. .save
2. .save
You're not creating the @photo
object in your create
method: 您不是在create
方法中创建@photo
对象:
def create
@photo = Photo.find(params[:id])
@person = @photo.persons.new(person_params)
if @person.anonymous == true
@person.commenter = "Anonymous"
else
@person.commenter = current_user.username
end
if @person.save
redirect_to photo(@photo)
else
redirect_to photos
end
end
private
def person_params
params.require(:photo).require(:params)
end
Could be more issues, but this what I found so far 可能还有更多问题,但这是我到目前为止发现的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.