{ -6ren">
gpt4 book ai didi

ruby-on-rails - 具有特定关系的 form_for 模型

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:46 25 4
gpt4 key购买 nike

我有
模型

class Group < ApplicationRecord
has_many :group_artists
has_many :singers, -> { where role: "Singer" }, class_name: "GroupArtist"
has_many :guitarists, -> { where role: "Guitarist" }, class_name: "GroupArtist"
end

class GroupArtist < ApplicationRecord
belongs_to :group
belongs_to :artist
end

class Artist < ApplicationRecord
has_many :group_artists
has_many :groups, through: :group_artists
end

group_artists 表有这些列

class CreateGroupArtists < ActiveRecord::Migration[5.1]
def change
create_table :group_artists, id: false do |t|
t.references :group, foreign_key: true, null: false
t.references :artist, foreign_key: true, null: false
t.string :role
t.string :acting

t.timestamps
end
end
end

Controller

class GroupsController < ApplicationController
def new
@group = Group.new

@singers = @group.singers.build
@guitarists = @group.guitarists.build

@artists = Artist.all // for a selection
end

def create
@group = Group.new(allowed_params)
@group.save
end

private

def allowed_params
params.require(:group).permit(:name, :singers, :guitarists, group_artists_attributes: [:group_id, :artist_id, :role, :acting])
end
end

views/groups/_form.html.erb

<%= form_for @group do |f| %>
<%= f.label "Singers" %>
<%= f.fields_for :singers do |singer| %>
<%= singer.select(:artist_id, @artists.collect { |a| [a.name, a.id.to_i] }, { include_blank: true }) %>
<% end %>
<%= f.label "Guitarists" %>
<%= f.fields_for :guitarists do |guitarist| %>
<%= guitarist.select(:artist_id, @artists.collect { |a| [a.name, a.id.to_i] }, { include_blank: true }) %>
<% end %>
<%= f.submit "Submit" %>
<% end %>

它可以创建组,但不会在 GroupArtist 中创建关系。我知道 Controller 部分缺少某些东西。我应该在“.build”之后添加一些东西,比如(角色:“歌手”),但它也没有做任何事情。

ruby -v 2.4.1
Rails -v 5.1.3

最佳答案

因为您使用的 group_artists 不仅仅是一个简单的连接表,您需要使用 nested attributes使用元数据创建一行:

class Group < ApplicationRecord
has_many :group_artists
has_many :singers, -> { where role: "Singer" }, class_name: "GroupArtist"
has_many :guitarists, -> { where role: "Guitarist" }, class_name: "GroupArtist"
accepts_nested_attributes_for :group_artists,
reject_if: ->{|a| a[:artist_id].blank? || a[:role].blank?}
end

此外,使用不同的关联来根据乐队成员的角色创建嵌套记录的结构并不是真正可扩展的 - 对于每个可能的角色,类/表单都会膨胀。

相反,您可能想使用两个选择:

<%= form_for @group do |f| %>
<fields_for :group_artists do |ga| %>
<div class="field">
<%= f.label :artist_id, "Artist" %>
<%= f.collection_select :artist_id, Artist.all, :id, :name %>
<%= f.label :role %>
<%= f.select :role, %w[ Singer Guitarist ] %>
</div>
<% end %>
<%= f.submit "Submit" %>
<% end %>

此外,您没有在 #create 方法中保存记录。

def create
@group = Group.new(allowed_params)
if @group.save
# ...
else
render :new
end
end

关于ruby-on-rails - 具有特定关系的 form_for 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com