ruby on rails - Model blank due to carrierwave gem - nested_attributes -
i've started learn ruby , ruby on rails, , first time have ask question on so, making me mad.
i'm programming rest api need receive image url , store in db.
for this, i've done model called imageset uses carrierwave store uploaded images this:
class imageset < activerecord::base has_one :template mount_uploader :icon1, icon1uploader mount_uploader :icon2, icon2uploader def icon1=(url) super(url) self.remote_icon1_url = url end def icon2=(url) super(url) self.remote_icon2_url = url end end
this icon1 , icon2 both received urls, hence setter override, , can't null. uploader classes creating versions whitelist of extensions , override of full_name.
then, have template class receives nested attributes imageset.
class template < activerecord::base belongs_to :image_set accepts_nested_attributes_for :image_set (other stuff) def image_set super || build_image_set end end
this model has image_set_id can't null.
considering simple request, post json:
{ "template": { "image_set_attributes": { "icon1": "http....", "icon2": "http...." } } }
it gives : imageset can't blank.
i can access temp.image_set
console,if temp
template
, , can set values there too, like, temp.image_set.icon = 'http...'
can't seem figure out why breaking there. should create image_set, set attributes save template class, assign id respective column in own model-
my controller doing:
(...) def create @template = template.create(params) if @template render status: 200 else render status: 422 end end private def params params.require(:template).permit(image_set_attributes: [:id, :icon1, :icon2]) end (...)
hope can give me tip on one.
thanks!
accepts_nested_attributes doesn't work expected belongs_to.
- don't use accepts_nested_attributes_for belongs_to
- does accepts_nested_attributes_for work belongs_to?
it can tricked working in circumstances, you're better off changing application elsewhere things "rails way."
templates
validate_presence_of :image_set
, right? if so, problem means imagesets must created before templates,accepts_nested_attributes
thinks template parent, , trying save parent first.the simplest thing can switch relationship, template
has_one :image_set
, , imagesetbelongs_to :template
. otherwise you're going have write rather odd controller logic deal params expected.
Comments
Post a Comment