我有两个模型:List
和Item
。在添加项目时,我需要list_id
:
这是我的代码:
在items_controler.rb
中def new
@item = Item.new
end
在app / models / item.rb
中class Item < ActiveRecord::Base
belongs_to :list
attr_accessible :list_id
end
这是我的表格:
<%= form_for(@item, remote: true, :html => { :role => "form" }) do |f| %>
<div id="error_explanation" class="bg-danger text-danger"></div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<%= f.label :name, :class => "control-label" %>
<%= f.text_field :name, :class => "form-control first_input" %>
</div>
<div class="form-group">
<%= f.label :color, :class => "control-label" %>
<%= f.text_field :color, :class => "form-control" %>
</div>
<div class="form-group">
<%= f.radio_button :priority, 'top', :checked => true %>
<%= label :priority_top, 'Place at the top of the list' %><br/>
<%= f.radio_button :priority, 'bottom' %>
<%= label :priority_bottom, 'Place at the bottom of the list' %>
<%= f.hidden_field :list_id, :value => params[:list_id] %>
</div>
<div class="form-group">
<%= f.submit @item.new_record? ? "Create Item" : "Update Item", :class => "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
现在他们在页面加载时收到错误
undefined method `attr_accessible' for #<Class:0xb3a2f928>
有没有不同的方法呢?
答案 0 :(得分:1)
如果您定义belongs_to :list
,则可以自动访问list
和list_id
属性,因此您无需定义任何属性访问者。
BTW,attr_accessible
自Rails 2.3.8以来已被弃用。
答案 1 :(得分:0)
您的Item类中不需要attr_accessible :list_id
:只需删除此行。
数据库应该有一个字段items.list_id
,Rails会自动为该字段设置getter / setter,而belongs_to关联将添加更多方法来处理item-&gt;列表关系。
如果要控制允许的参数,请在控制器中执行。
答案 2 :(得分:0)
看起来你需要nested resources
:
#config/routes.rb
resources :lists do
resources :items, only: [:new, :create] #-> url.com/lists/:list_id/items/new
end
#app/controllers/items_controller.rb
class ItemsController < ApplicationController
def new
@list = List.find params[:list_id]
@item = @list.items.new
end
def create
@list = List.find params[:list_id]
@item = @list.items.new list_params
@item.save
end
private
def list_params
params.require(:list).permit(:x, :y, :z)
end
end
这将允许您访问list
对象,并创建一个嵌套的items
对象供其使用。
-
您必须更改form_for
以使用嵌套路径路径:
<%= form_for [@list, @item] do |f| %>