database - How do I update two models with one form in Ruby on Rails? -
i have 2 models, page , pagecontent.
class page < activerecord::base has_many :page_contents end class pagecontent < activerecord::base belongs_to :page end
page has :css_design attribute, want able edit attribute pagecontent form. ideas?
i see lot of accepts_nested_attributes , fields_for advice, don't work, because seem forms either a. creating entire new instances of different model form (for example, creating tasks project form), or b. updating associated records thru parent. i want opposite- want update parent's record thru associated records.
any appreciated! many in advance!
--mark
update
i have added following pagecontent model:
def css_design page ? page.css_design : nil end def css_design= (val) if page page.update_attribute 'css_design', val else @css_design = val end end after_create :set_page_css_design_on_create def set_page_css_design_on_create self.css_design = @css_design if page && @css_design end
and have, in both create , update actions:
@page_content.update_attributes params[:page_content]
but i'm getting:
nomethoderror (undefined method `css_design=' #<page:0x00000003a80338>): app/models/page_content.rb:13:in `css_design=' app/controllers/page_contents_controller.rb:56:in `new' app/controllers/page_contents_controller.rb:56:in `create'
when go create page_content first time. copied , pasted stuff straight files, if see weird, please let me know!
update model following:
class pagecontent < activerecord::base belongs_to :page def css_design page ? page.css_design : nil end def css_design= (val) if page page.update_attribute 'css_design', val else @css_design = val end end after_create :set_page_css_design_on_create def set_page_css_design_on_create self.css_design = @css_design if page && @css_design end end
your form can display , update current page's value, though looks it's handling pagecontent:
<%= form_for @page_content |f| %> ... <%= f.text_field :css_design %> ... <% end %>
in controller, e.g.:
def update ... @page_content.update_attributes params[:page_content] ... end
Comments
Post a Comment