How to create an association between two rails models

后端 未结 5 1130
南笙
南笙 2021-01-16 12:07

This is a newbie question, but I\'m still learning how to create an association between two models in rails. I have a user model and a journal_entry model. The journal entri

相关标签:
5条回答
  • 2021-01-16 12:42

    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
    
    0 讨论(0)
  • 2021-01-16 12:47

    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
        ..
    
    0 讨论(0)
  • 2021-01-16 12:48

    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.

    0 讨论(0)
  • 2021-01-16 12:49

    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!

    0 讨论(0)
  • 2021-01-16 13:01

    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.

    0 讨论(0)
提交回复
热议问题