繁体   English   中英

保存后无法访问模型的ID?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM