【发布时间】:2013-11-30 02:55:42
【问题描述】:
我是一个新的 Rails 用户。这可能是一个非常基本的问题,但我需要帮助
我正在制作一个具有多对多关系的 Bands 表、Festivals 表和 Participations 表的应用程序。我的模型如下:
class Band < ActiveRecord::Base
attr_accessible :year, :genere, :name, :country
has_many :participations
has_many :festivals, :though => :participations
end
class Festival < ActiveRecord::Base
attr_accessible :city, :name, :country
has_many :participations
has_many :bands, :through => :participations
end
class Participation < ActiveRecord::Base
attr_accessible :year
belongs_to :band
belongs_to :festival
end
当我使用rails server 执行我的应用程序时,我可以正常访问 localhost:3000/bands 和 /festivals,并且新的乐队页面运行良好。当我访问 localhost:3000/participations 时,它会正常加载(并显示一个包含 id 和年份的空表),但单击新的参与会显示以下错误:
undefined method `bands_id' for #<Participation:0xba1a5760>
Extracted source (around line #16):
13:
14: <div class="field">
15: <%= f.label :bands_id %><br />
16: <%= f.number_field :bands_id %>
17: </div>
18: <div class="field">
19: <%= f.label :festivals_id %><br />
Trace of template inclusion: app/views/participations/new.html.erb
Rails.root: /home/User/apps/festnum
我是一个新的 Rails 用户,不确定如何更改参与表的视图控制器。 谢谢!
PD:我也想知道如何在参与创建页面中添加一个下拉菜单,其中包含已创建的音乐节和乐队。
编辑:之前的问题已经解决。但是,我仍在寻找一种方法,在参与创建页面中使用已经创建的节日和乐队制作下拉菜单,如果它可以使用节日名称而不是 id 更好。另一个问题:当我访问创建新参与页面时,我用我已经创建的节日和乐队的数据填写字段(两个字段的 ID 1,我在数据库中使用了 SELECT 语句并确保这些条目已经存在),我收到以下错误:
找不到没有 ID 的节日。
我很确定错误就在这里:(在参与控制器处)
def create
@participation = Band.new(params[:band])
@participation.festivals << Festival.find(params[:festival_id])
respond_to do |format|
if @participation.save
format.html { redirect_to @participation, notice: 'Participation was $
format.json { render json: @participation, status: :created, location:$
else
format.html { render action: "new" }
format.json { render json: @participation.errors, status: :unprocessab$
end
end
结束
你能再帮我一次吗?
【问题讨论】:
-
请添加您构建表单的视图代码。您似乎使用了错误的字段名称 - 我想您需要
f.number_field :band_id和f.number_field :festival_id
标签: ruby-on-rails ruby ruby-on-rails-3.2 many-to-many has-many-through