0

这应该有点简单,但似乎无法掌握关联。

我正在使用nested_form 和回形针。我有一个名为 photo 的模型来存储所有图像和一个帖子模型。我正在尝试显示与相关帖子关联的照片,但在渲染视图时出现“未定义的方法头像”。

class Post < ActiveRecord::Base
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos
attr_accessible :title, :comments, :photo_id, :avatar, :photos_attributes
end

Class Photo < ActiveRecord::Base
belongs_to :post
attr_accessible :avatar, :post_id
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

控制器

def new
@post = Post.new
@post.photos.build
end

所以我的印象是,当建立一个帖子时,帖子和照片模型之间会建立关联吗?是对的吗?

所以当我在视图中调用它时,我得到了未定义的方法,谁能告诉我哪里出错了

<% @posts.each do |f| %>
<ul>
 <li><%= f.title %></li>
 <li><%= f.department.name %></li>
 <li><%= image_tag f.avatar.url(:thumb) %></li>
 <li><%= link_to "Delete Post", post_path(f.id), :confirm => "Are you sure?", :method => :delete %></li>
</ul>
<% end %>

我试过了

<%= image_tag f.photo.avatar.url(:thumb) %>

但这也不起作用

4

3 回答 3

2

可能是您创建错误的照片。

在这里您可以看到表单的外观:使用回形针的嵌套表单

而且Post has_many :photos,所以它必须是somth。像

<% @posts.each do |f| %>
....


 <% f.photos.each do |photo| %>
   <%= image_tag photo.avatar.url(:thumb) %>
 <% end %>


...
<% end %>
于 2013-02-01T17:27:51.563 回答
1

当我使用嵌套属性时,我遵循三个步骤。首先,在父模型中你可以使用accepts_nested_attributes_for:

Class Post
  has_many :photos, dependent: :destroy
  accepts_nested_attributes_for :photos
  attr_accessible :photos_attributes
end

其次,您可以为照片合并一个嵌套表单,以便您可以为该特定帖子设置照片的属性:

<%= form_for(@post) do |f| %>
  <%= f.fields_for :photos do |p| %>
  ...rest of form here...

第三,您可以通过post模型中的新动作创建照片:

Class UserController
  def new
    @user = User.new(photos: Photo.new)
  end
end

最后一步很重要。如果您不这样做,否则您将看不到用户表单中的照片字段。如果您按照这些步骤操作,您应该能够在用户表单中设置照片和用户的所有属性。

于 2013-02-01T19:47:30.817 回答
0

我认为在您的控制器中,您应该首先定义post您要关联的对象:

 def new
   @post = Post.find(params[:post_id]
   @photo = @post.photos.build

  ....
  end

create动作也是如此PhotosController

于 2013-02-01T17:24:22.400 回答