How to create an association between two rails models

孤者浪人 提交于 2019-12-01 12:39:35

i bet, that u forget something like

def create
    @journal_entry = @user.journal_entries.build(params[:journal_entry])
    # @journal_entry = current_user.journal_entries.build(params[:journal_entry])
    if @journal_entry.save
    ..

journal_entry model should look like

class JournalEntry < ActiveRecord::Base
  attr_accessible :post, :title, :user_id
  belongs_to :user
  validates :user_id, presence: true
  default_scope order: 'journal_entries.created_at DESC'
end

This should work!

You need to add user_id to your attr_accessible call, if you look at your logs it is probably warning you that it can't mass assign it.

Ok, so I got this working by adding the user to the create action in my journal_entries_controller.rb. Here's the code I used, but is this the "rails way" to do this?

def create
  @user = current_user
  @journal_entry = @user.journal_entries.build(params[:journal_entry])
  if @journal_entry.save
    flash[:success] = "Journal entry created!" 
  end
end

you have it right this time. You added the user association to the journal model which loads the user in the controller before displaying it in the view. You do need the hidden fields in your form which you added, since you are using a stateless protocol. On the update/create action, double check that the user posting is the user using and save.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!