【发布时间】:2012-01-11 18:48:21
【问题描述】:
这里有几个问题coverthisalready,我知道。我是编程和 Rails 的新手,所以请多多包涵。我的目标是收集n 标签对象并将它们显示在我的显示和索引操作中。
更新
感谢两位回答的人。每个建议都将我推向了正确的方向。我可以通过传入一个空数组来初始化 tags 对象,从而获得创建帖子的 rake 任务。但是仍然没有创建标签。经过进一步检查,我得到以下 SQL 异常:
irb(main):002:0> u.posts.build(title: "a new day", tags: "jump")
WARNING: Can't mass-assign protected attributes: tags
(1.7ms) SELECT 1 FROM "posts" WHERE "posts"."title" = 'a new day' LIMIT 1
(0.5ms) COMMIT
=> #<Post id: nil, title: "a new day", description: nil, content: nil, user_id: 1, created_at: nil, updated_at: nil>
我的设置如下:
Tag模特
class Tag < ActiveRecord::Base
belongs_to :post
end
Post型号
class Post < ActiveRecord::Base
has_many :tags, autosave: true
attr_accessible :title, :description, :content, :tags_attributes
accepts_nested_attributes_for :tags, allow_destroy: true, reject_if: lambda {|attrs| attrs.all? {|key, value| value.blank?}}
#add n number of form fields to capture tags in each article.
def with_blank_tags(n = 3)
n.times do
tags.build
end
self
end
end
'查看'代码
<%= form_for(@post.with_blank_tags) do |f| %>
<div class="field">
<%= f.fields_for(:tags) do |tags| %>
<%= unless tags.object.new_record? tags.check_box('_destroy') + tags.label('_destroy', 'Remove Tag') end%>
<%= tags.label :tags, "Add a Tag"%>
<%= tags.text_field :tags %>
<%end%>
</div>
<%end%>
“控制器”代码
def new
@post = @user.posts.build
end
def create
@post = @user.posts.build(params[:post])
if @post.save?
respond_to do |format|
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
我的耙子任务:
namespace :db do
desc "Fill database with sample data"
task :posts => :environment do
Rake::Task['db:reset'].invoke
make_users
make_posts
end
end
def make_users
puts "making users..."
5.times do |n|
name = Faker::Name.name
password = "foo"
email = "example-#{n+1}@example.com"
@user=User.create!(
codename: name,
email: email,
password: password,
password_confirmation: password)
end
end
def make_posts
puts "making posts..."
User.all(:limit => 3).each do |user|
10.times do
content = Faker::Lorem.paragraphs(3)
description = Faker::Lorem.words(10)
title = Faker::Lorem.words(4)
tag = []
post = user.posts.create!(title: title, description: description, content: content, tags_attributes: tag)
end
end
end
【问题讨论】:
-
如果这很重要,我会感到惊讶。但是到目前为止,我在网上看到的许多其他问题和示例在 attr_accessible 调用之前都有接受嵌套属性调用。是否需要在将 #{name}_attributes 列入白名单之前对其进行定义?
-
@agmcleod 我按照您建议的顺序拨打电话并收到了同样的异常。
-
@agmcleod 我在post 中遇到了一个建议重命名模型的解决方案。我想知道模型的名称标签是否不可接受?
标签: ruby-on-rails ruby-on-rails-3 model nested-attributes