[英]Can't access id of a model after saving?
我正在嘗試鏈接到嵌套模型,但是,該ID似乎不存在。
以這種形式,我有以下內容
<% @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 %>
但是,似乎ans沒有id? 我已經通過form_for創建了模型,但是無法訪問其ID。 這是我為人創造的行動
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
有任何想法嗎?
1.“人”
雖然Rails會自然變復數person
作為people
,你有你的協會成立為?
你應該有這個:
#app/models/photo.rb
Class Photo < ActiveRecord::Base
has_many :persons, class_name: "Person"
end
2. .save
您不是在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
可能還有更多問題,但這是我到目前為止發現的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.