我无法得到我做错的事。
我正在修改railscast#102。
我有型号文章:
belongs_to :category
def category_name
category.try(:name)
end
def category_name=(name)
self.category = Category.find_by_name(name)
end
Category.rb:
has_many :articles
Create_categories迁移:
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
Create_articles:
def change
create_table :articles do |t|
t.string :name
t.text :content
t.integer :category_id
t.timestamps
end
end
和来自_form的代码:
<div class="field">
<%= f.label :category_name %><br />
<%= f.text_field :category_name %>
</div>
提交后我收到此错误:
Can't mass-assign protected attribute :category_name
修改
def create
@article = Article.new(params[:article])
respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
else
format.html { render action: "new" }
end
end
end
我的日志:
Started PUT "/articles/4" for 127.0.0.1 at 2012-10-16 00:59:44 +0300
Processing by ArticlesController#update as HTML
Parameters: {"utf8"=>"тЬУ", "authenticity_token"=>"YDPlS//tXg6Adl1npEEyNNBMZI0
a7hW8bV5XFPmRre4=", "article"=>{"name"=>"112312", "category_name"=>"asdasd"}, "c
ommit"=>"Update Article", "id"=>"4"}
←[1m←[35mArticle Load (0.0ms)←[0m SELECT "articles".* FROM "articles" WHERE "
articles"."id" = ? LIMIT 1 [["id", "4"]]
←[1m←[36m (0.0ms)←[0m ←[1mbegin transaction←[0m
←[1m←[35mCategory Load (0.0ms)←[0m SELECT "categories".* FROM "categories"
WHERE "categories"."name" = 'asdasd' LIMIT 1
←[1m←[36m (0.0ms)←[0m ←[1mcommit transaction←[0m
Redirected to http://127.0.0.1:3000/articles/4
Completed 302 Found in 16ms (ActiveRecord: 0.0ms)
所以它似乎在拯救,但我认为在我看来并不是这样:
<p>
<b>Category:</b>
<%= @article.category %>
</p>
给我空白。
答案 0 :(得分:2)
要使此行生效<%= f.text_field :category_name %>
,请将此行添加到Article
模型
attr_accessible :category_name
如果您已经尝试过,请确保在调用迁移后重新启动Web服务器。