在Rails 3.1中,如何为具有belongs_to关联的表单创建选择列表?
胃肠道间质瘤在这里: https://gist.github.com/1553371
这些是我拥有的模型:
class Character < ActiveRecord::Base
has_many :weapons
end
class Weapon < ActiveRecord::Base
belongs_to :character
end
这就是我的模型HAML 中的视图看起来像:
= form_for(@weapon) do |f|
%ul.fields
%li
= f.label :character
= collection_select :weapon, :character_id, Character.all, :id, :name, {:prompt => 'Please Select a Character.'}
但我不断收到此错误:
undefined method `character_id' for #<Weapon:0x007f9033232088>
我尝试使用字符串作为 character_id
,但这也不起作用。表单以 :character
呈现,但当然它不会保存回来,因为它需要 id
。
GIST is here:
https://gist.github.com/1553371
These are the models I have:
class Character < ActiveRecord::Base
has_many :weapons
end
class Weapon < ActiveRecord::Base
belongs_to :character
end
and this is what my view in HAML looks like:
= form_for(@weapon) do |f|
%ul.fields
%li
= f.label :character
= collection_select :weapon, :character_id, Character.all, :id, :name, {:prompt => 'Please Select a Character.'}
but I keep getting this error:
undefined method `character_id' for #<Weapon:0x007f9033232088>
I've attempted using a string for character_id
, that also didn't work. The form renders with :character
, but then of course it won't save back since it needs the id
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码看起来不错,很可能您的武器模型上没有
character_id
字段。如果您这样做,则您有需要运行的待处理迁移。您可以通过查看
db/schema.db
来检查数据库的当前状态,它将显示您是否有character_id列。您可以使用
rake db:migrate
运行迁移,然后使用rake db:test:prepare
更新测试数据库。如果运行迁移后它不起作用,那么您需要创建一个,应该类似于:
Your code looks fine, it's likely that you don't have a
character_id
field on your weapon model. If you do then you have pending migrations that need to be run.You can check the current state of your database by looking at
db/schema.db
it will show if you have the character_id column or not.You can run your migrations using
rake db:migrate
then userake db:test:prepare
to update your test database as well.If it's not working after running migrations then you'll need to create one, should look something like:
api 文档:
所以你想要
The api docs:
So you want