Reputation: 8585
I'm following railscasts for jcrop but was wondering how do I have a dynamic model name in jquery if I have something like this:
update: (coords) =>
$('#user_crop_x').val(coords.x)
$('#user_crop_y').val(coords.y)
$('#user_crop_w').val(coords.w)
$('#user_crop_h').val(coords.h)
@updatePreview(coords)
#user
is based on user's model, but it was hard coded, but if I have other models with cropping, how do you make the id dynamic based on the model?
Thanks
Upvotes: 0
Views: 327
Reputation: 481
andrewliu. I don't what about dynamic model mean. I talk about how to use another model name to use jcrop.
update: (coords) =>
$('#user_crop_x').val(coords.x)
$('#user_crop_y').val(coords.y)
$('#user_crop_w').val(coords.w)
$('#user_crop_h').val(coords.h)
@updatePreview(coords)
The #user_crop_x
is come from this form:
= form_for MODEL, url: CROP_URL, method: :patch, html:{id: "jcrop_form"} do |f|
- %w[x y w h].each do |attribute|
= f.hidden_field "crop_#{attribute}"
.form-actions
= f.submit t(".crop"), class: 'btn btn-primary'
It will default generate many id in the hidden_field in rails's form_for
. Just like #user_crop_x
and #user_crop_y
and so on.
The default id is a certain rule what is ##{model_name}_{attribute_name}
, so if you have dynamic model
and the best way is set the class name in the hidden_field. Example:
= f.hidden_field "crop_#{attribute}", class: "crop_class_#{attribute}"
And set the jQuery code like:
update: (coords) =>
$('.crop_class_x').val(coords.x)
$('.crop_class_y').val(coords.y)
$('.crop_class_w').val(coords.w)
$('.crop_class_h').val(coords.h)
@updatePreview(coords)
Upvotes: 1
Reputation: 1371
If your coffeescript is rendered dynamically (ie in a view.js.erb file), then you can just use a shared variable like so:
users_controller: Assign a shared variable that you can use in your view, for example:
@user_name = User.find(1).name
view
update: (coords) =>
$('#<%= @user_name %>_crop_x').val(coords.x)
$('#<%= @user_name %>_crop_y').val(coords.y)
$('#<%= @user_name %>_crop_w').val(coords.w)
$('#<%= @user_name %>_crop_h').val(coords.h)
@updatePreview(coords)
Upvotes: 0