我的rails应用程序中有三个模型。当我创建新通知时,如何重写notification_controller.rb和notifications / new.html.erb中的表单,以便将条目保存到notifications_users表中?感谢
schema.rb
create_table "notifications", force: :cascade do |t|
t.string "title"
t.string "first_name"
t.string "last_name"
t.datetime "date"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "notifications_users", id: false, force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "notification_id", null: false
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "user_type"
t.string "username"
t.string "password"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.index ["username"], name: "index_users_on_username", unique: true
end
new.html.erb
<h1>New Message</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@notification, url: notifications_new_path) do |f| %>
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'form-control' %>
<%= f.label :date %>
<%= f.datetime_field :date %>
<%= f.label :content %>
<%= f.text_area :content, class: 'form-control' %>
<%= f.submit "Create my message", class: "btn btn-primary" %>
<% end %>
notifications_controller.rb
def create
@notification = Notification.new(notification_params)
if @notification.save
flash[:success] = "Notification created!"
redirect_to @notification
else
render 'new'
end
end
答案 0 :(得分:1)
所以你想在这里创建两个记录,一个Notification
记录和一个NotificationUser
记录。有很多方法可以做到这一点,例如:
...
@notification = Notification.new(notification_params)
if @notification.save
NotificationUser.create(user_id: USER_ID_HERE, notification_id: @notification.id) # OR NotificationUser.create(user: USER_RECORD_HERE, notification: @notification) OR @notification.users << USER_RECORD_HERE
...