So I have 2 models, Comment and Picture. A Comment has one Picture if
the users so chooses, but when someone is creating a Comment, it would
of course call the create method in the Comment Controller. However, I
want it to create a Picture as well. I could add it to the create
method in the Comment Controller, but that does not seem very DRY. Is
there a way I can do this?
Question is not clear, do you want to create an empty picture record
anyway?
Hi Mike Chai
What I understood is you have relations like
comment has_one picture
picture belongs_to comment
As an example
comment name:string
picture name:string,comment_id:integer
So do as below
in comments_controller new action
@comment = Comment.new
@comment.picture = Picture.new
Now in view/comments/new.html.erb
<% form_for(@comment) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<% f.fields_for :picture do |p| %> <%= p.text_field :name %> <% end %>
<%= f.submit 'Create' %>
<% end %> in model Comment write (modify this according to your needs)
has_one :picture,:dependent => :destroy
accepts_nested_attributes_for :picture,:reject_if => proc { |attributes|
attributes[‘name’].blank? }
in create action of comments controller
@comment = Comment.new(params[:comment])
@comment.save
Thats all…Modify the rest of your code like this…This is just an
example
Sijo
And assuming you are on rails 2.3