[英]Inserting a record in a table having foreign key - Ruby on Rails
class UserPreference < ActiveRecord::Base
belongs_to :user_job
belongs_to :preference
end
class Preference < ActiveRecord::Base
belongs_to :days
belongs_to :location
belongs_to :time_pref
has_one :user_preference, :foreign_key => 'prefer1_id', :dependent => :destroy, :class_name => "UserPreference"
has_one :other_user_preference, :foreign_key => 'prefer2_id', :dependent => :destroy, :class_name => "UserPreference"
end
我有這兩個模型。 我正在嘗試創建一個表單,可以在其中選擇用戶並使用下拉列表選擇他們的首選項。
%= form_for @user_preference, url: {action: "create"} do |f| %>
<%= select_tag(:user_id, options_for_select(@user_options)) %>
<p><p> Preference 1 :
<%= select_tag(:days_id, options_for_select(@day_options)) %>
<%= select_tag(:location_id, options_for_select(@building_options)) %>
<%= select_tag(:time_id, options_for_select(@time_slot_options)) %>
</p>
<p> Preference 2 :
<%= select_tag(:days_id, options_for_select(@day_options)) %>
<%= select_tag(:location_id, options_for_select(@location_id)) %>
<%= select_tag(:time_pref_id, options_for_select(@time_pref_id)) %>
</p>
<%= f.submit "Submit" %>
這使我可以選擇用戶並選擇他們的偏好。 但是,如何使用外鍵將它們實際插入preferred1_id和preferred2_id? 如果我使用上面顯示的形式,則不會得到兩組不同的首選項,而只會得到第二組下拉列表中的選擇。
我希望做這樣的事情(或其他代碼)在表中創建新記錄。
def create
@pref = preference.new(params[:pref])
redirect_to @pref
end
如何去做呢? 我是Rails的初學者。
我可以給你個主意。
1.首先更新您的關聯。
2.通過使用用戶首選項和嵌套表格來實現表格。
您的用戶首選項類應如下所示:
class UserPreference < ActiveRecord::Base
belongs_to :user_job
has_one :preference_one, :foreign_key => 'prefer1_id', :dependent => :destroy, :class_name => "UserPreference"
has_one :preference_two, :foreign_key => 'prefer2_id', :dependent => :destroy, :class_name => "UserPreference"
accepts_nested_attributes_for :preference_one # configure your options
accepts_nested_attributes_for :preference_two # configure your options
end
class Preference < ActiveRecord::Base
# ...
belongs_to :user_preference, :foreign_key => 'prefer1_id', :dependent => :destroy, :class_name => "UserPreference"
belongs_to :other_user_preference, :foreign_key => 'prefer2_id', :dependent => :destroy, :class_name => "UserPreference"
end
現在在您的控制器中:
def new
@user_preference = UserPreference.new
@user_preference.build_preference_one
@user_preference.build_preference_two
end
def create
@user_preference = UserPreference.new(user_preference_params)
# make sure you add your nested attributes on the permitted param list.
end
以您的形式:
在我們基於新操作的基礎上,將字段用於兩個單獨的關聯。
如果解決此問題,這就是設計表單的方式。 好處:
1.可維護的代碼
2.控制器中的代碼更少
3.更加靈活地承擔單位責任。
盡管考慮到語法錯誤,您仍可以遵循這種模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.