使用关联创建记录 - 活动管理员

时间:2013-12-04 11:31:51

标签: ruby-on-rails ruby-on-rails-4 associations activeadmin

我正在使用主动管理员,似乎正在努力创建一个关联记录。我已经按正常方式设置了

class Membership < ActiveRecord::Base
belongs_to :member
attr_accessible :membership_type

end

class Member < ActiveRecord::Base
 has_one :membership
 accepts_nested_attributes_for :membership
 attr_accessible :membership_attributes, :forename, :middlename, :surname, :house_no, :house_name, :street, :town, :postcode, :home_tel, :mobile_tel, :work_tel, :email

end

然后我想以相同的形式创建一个新成员及其成员资格类型,所以我的member.rb到目前为止看起来像这样

ActiveAdmin.register Member do
# Set Which Columns are to be displayed on the index page
index do
column :forename
column :middlename
column :surname
column :house_no
column :house_name
column :street
column :town
column :postcode
column :home_tel
column :mobile_tel
column :work_tel
column :email

column :membership do |member|
  member.membership.map{ |ms| ms.membership_type}
end

default_actions
end
# Set Which Columns are to be displayed on Create New Member
form do |f|
 f.inputs "Member Registration" do
 f.input :forename
 f.input :middlename
 f.input :surname
 f.input :house_no
 f.input :house_name
 f.input :street
 f.input :town
 f.input :postcode
 f.input :home_tel
 f.input :mobile_tel
 f.input :work_tel
 f.input :email
 end
  f.inputs :for => [:membership, f.object.membership || Membership.new] do |m|
   m.input :membership_type, :label => 'Membership Type', :as => :select, :collection => Membership.all.map{|m| [m.membership_type]} 

end 
  f.actions
end

end

这会显示一个选择框,我可以从各种会员类型中进行选择,但在创建记录时我似乎没有传递正确的值,

这是发布内容的一个示例

member[forename]:Name 1
member[middlename]:Name 2
member[surname]:Name 3
member[house_no]:1
member[house_name]:
member[street]:Test Street
member[town]:Test Town
member[postcode]:CF23 7BD
member[home_tel]:01633222222
member[mobile_tel]:07864582356
member[work_tel]:01633555555
member[email]:test@mail.com
membership_attributes"=>{"membership_type"=>"Student"}
commit:Create Member 

这似乎不对吗?当我尝试查看记录时

column :memberships do |member|
  member.memberships.map{ |ms| ms.membership_type}
end

我收到以下mysql错误

Mysql2::Error: Unknown column 'memberships.member_id' in 'where clause': SELECT `memberships`.* FROM `memberships`  WHERE `memberships`.`member_id` = 10

有人能指出我正确的方向吗或任何人都可以看到我出错的地方?

非常感谢

2 个答案:

答案 0 :(得分:1)

而不是f.input :memberships试试这个:

f.has_many :memberships do |pf|
    pf.input :membership_type
end

并关闭您的成员对象字段

f.inputs "Member Registration" do
    f.input :forename
    f.input :middlename
    f.input :surname
    ...
end

所以你的表格应该是这样的:

form do |f|
  f.inputs "Member Registration" do
    f.input :forename
    f.input :middlename
    f.input :surname
    # .. the rest of your fields
  end
  f.has_many :memberships do |pf|
    pf.input :membership_type
  end
  f.actions
end

答案 1 :(得分:0)

关于MySQL错误,我认为要使关联工作,您需要将列member_id添加到成员资格表。您可以使用

创建迁移
rails g migration add_member_id_to_memberships member_id:integer

然后使用

进行迁移
bundle exec rake db:migrate