In rails default controller the new method makes an object, and the create method is used later to save that.
I want to set a mod_user field in the DB, without it being input into the form.
Based on this link http://api.rubyonrails.org/classes/ActiveRecord/Base.html I've tried adding the following to my pages controller.
def new
@page = Page.new(:n_publisher_id => session[:n_publisher_id])
or
def create
page = Page.new(params[:page])
page.n_publisher_id = session[:n_publisher_id]
But it is saving as NULL If I put this in the controller and model then I get nil object errors from ActiveRecord
def new
@page = Page.new(1)
def initialize(n_publisher)
@n_publisher_id = n_publisher
end
I have attr_accessor :n_publisher_id included in my page model. This works in the console...
>> @i = Page.new
=> #<Page id: nil, fk_issue: nil, n_status_id: nil, dt_published_datetime: nil, dt_offline_date: nil, dt_created_date: nil, n_publisher_id: nil, created_at: nil, updated_at: nil, page_name: nil>
>> @i.n_publisher_id
=> nil
>> @i.n_publisher_id = 1
=> 1
>> @i.n_publisher_id
=> 1
Here is schema of the pages table
mysql> show fields from pages;
+-----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| fk_issue | int(11) | YES | | NULL | |
| n_status_id | int(11) | YES | | NULL | |
| dt_published_datetime | datetime | YES | | NULL | |
| dt_offline_date | datetime | YES | | NULL | |
| dt_created_date | date | YES | | NULL | |
| n_publisher_id | int(11) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| page_name | varchar(255) | YES | | NULL | |
+-----------------------+--------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)
Here is the model
class Page < ActiveRecord::Base
has_many :slots, :dependent => :destroy
accepts_nested_attributes_for :slots
#attr_accessor :n_publisher_id
#attr_accessible :n_publisher_id
end
Create Action
def create
page = Page.new(params[:page].merge({:n_publisher_id => 1}))
#page.dt_created_date = Date.today
page.n_publisher_id = 1
respond_to do |format|
if page.save
format.html { redirect_to(page, :notice => 'Page was successfully created.') }
format.xml { render :xml => page, :status => :created, :location => page }
else
format.html { render :action => "new" }
format.xml { render :xml => page.errors, :status => :unprocessable_entity }
end
end
end