ruby on rails - how to add the current user_id automatically to another table? -
i've been playing models bit.
i using devise
my schema:
create_table "complaints", force: :cascade |t| t.string "title" t.text "complaint_info" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" end add_index "complaints", ["user_id"], name: "index_complaints_on_user_id", using: :btree create_table "users", force: :cascade |t| ... end
complaint model:
class complaint < activerecord::base belongs_to :user validates :title, presence: true end
users model:
class user < activerecord::base # include default devise modules. others available are: # :confirmable, :lockable, :timeoutable , :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :complaints end
i assuming setup rails assume current_user id goes inside user_id it's not storing it, have manually in controller this:
def create @complaint = complaint.new(complaint_params) |c| c.user_id = current_user.id end if @complaint.save redirect_to dashboard_complaint_path(@complaint) else render 'new' end end private def complaint_params params.require(:complaint).permit(:title, :complaint_info) end
is right way it? thanks.
for rails automatically set foreign key need create new record through parent records association.
@complaint = current_user.complaints.new(complaint_params)
Comments
Post a Comment