I have two models User and Recipe. I want to get user fields on recipe page and username in each recipe on user page. I don't know how to do it. In rails i have two has many association between User and Recipe. I added examples of my json arrays that I'm getting from rails.
My json user array
user: {
id: 1,
name: "ejiqpep",
email: "ejiqpep#gmail.com",
recipe_ids: [
1,
2
],
box_recipe_ids: [
1,
2
]
}
My json recipe array
recipe: {
id: 1,
title: "recipe01",
about: "about01",
ingredients: "ingredients01",
steps: "steps01",
visibility_type: true,
slug: "recipe01",
user: {
id: 1,
name: "ejiqpep",
email: "ejiqpep#gmail.com",
recipe_ids: [
1,
2
],
box_recipe_ids: [
1,
2
]
}
}
user.js.coffee
App.User = DS.Model.extend
name: DS.attr('string')
email: DS.attr('string')
recipes: DS.hasMany('App.Recipe')
box_recipes: DS.hasMany('App.Recipe')
recipe.js.coffee
App.Recipe = DS.Model.extend
user: DS.belongsTo('App.User')
title: DS.attr('string')
user.handlebars (I want to get user name in each recipe)
<h1>{{name}}</h1>
<p><b>Email:</b> {{email}}</p>
<h3>User recipes</h3>
{{#each recipe in recipes}}
<div>
<span>{{recipe.id}}</span>
<span>!!!I want to show username here!!!</span>
<span>{{#linkTo recipe recipe}} {{recipe.title}} {{/linkTo}}</span>
</div>
{{/each}}
<h3>User box_recipes</h3>
{{#each fav in box_recipes}}
<div>
<span>{{fav.id}}</span>
<span>!!!I want to show username here!!!</span>
<span>{{#linkTo recipe fav}} {{fav.title}} {{/linkTo}}</span>
</div>
{{/each}}
recipe.handlebars
<h1>{{title}}</h1>
<p>User {{user.name}}</p> # I want to show username here!!!
i donĀ“t know exactly if it works ... but give it a try :
update:
{{#each recipes}}
<div>
<span>{{id}}</span>
<span>{{../name}}!!!I want to show username here!!!</span>
<span>{{#linkTo recipe this}} {{title}} {{/linkTo}}</span>
</div>
{{/each}}
Related
I have a model Usergroup which has 2 attributes which are arrays:
Usergroup.create(name: "Group 1", account_id: 7, hix_modules: ['cs-seh','cs-ddr'], users: [61,83,77])
Now I want to create a form to create a usergroup. What is the best way to do this for the array attributes? I'm thinking of using selects combined with either Cocoon or Stimulus in the end to add a variable number of users or hix_modules. But to start simple with just one fixed select: how does it look like to send a valid array to the controller?
edit your model to make the field serialized to an array
class Usergroup < ActiveRecord::Base
serialize :hix_modules,Array
serialize :users,Array
end
test it out in console
a = Usergroup.new
=> #<Usergroup id: nil, hix_modules: [], users: [], name: nil, account_id: nil, created_at: nil, updated_at: nil>
a.hix_modules
=> []
a.hix_modules << "cs-seh"
=> ["cs-seh"]
I soled it by using a multi select:
= f.select :hix_modules, options_for_select(#hix_modules), { prompt: "Select module" }, { multiple: true, size: 10}
This sends these params values:
Parameters: {"usergroup"=>{"account_id"=>"7", "name"=>"Test", "hix_modules"=>["", "CS-Agenda", "CS-DDR"], "users"=>["", "65", "77", "46"]}
I have three models using Active Record associations:
Book Model
has_many :checkouts
User Model
has_many :checkouts
Checkout Model
belongs_to :book
belongs_to :user
In my view, I need the book, checkout, and user names from the checkouts.
By using Book.first.checkouts I get:
#<ActiveRecord::AssociationRelation
[#<Checkout id: 30,
checkout_date: "2017-04-13",
return_date: nil,
book_id: 118,
user_id: 1,
created_at: "2017-04-13 17:43:07",
updated_at: "2017-04-13 17:43:07"
>,#<Checkout id: 50,
checkout_date: "2017-04-13",
return_date: nil,
book_id: 118,
user_id: 1,
created_at: "2017-04-14 00:33:34",
updated_at: "2017-04-14 00:33:34">
]>
But, I would like to the user name, not just the id. I've tried Book.first.checkouts.map { |c| c.user.name } but that returns only the name, and I need the rest of the checkout information. Ideally, my data (converted to json) looks something like:
{
name: "Book Name",
checkouts: [
checkout_data: "Today",
user_name: "Mary"
]
}
How can I add the user name to my checkout data?
You can try this at your controller:
render json: #books, include: { checkout: { only: :checkout_date, include: { user: { only: :name } } }}
You should preload the data to prevent (N+1) query problem,
For Display possible checkouts for particular book:
book_id = <given book id>
book = Book.find(book_id)
checkouts = book.checkouts.includes(:user)
return_hash = {name: book.name, checkouts: []}
checkouts.each do |checkout|
return_hash[:checkouts] << { checkout_data: checkout.checkout_date,
user_name: checkout.user.name
}
end
To include other solutions, I found this worked pretty well:
checkouts = book.checkouts.unreturned.map do |checkout|
checkout.attributes.merge({ user_name: checkout.user.name })
end
{ checkouts: checkouts, available: book.available?, book_id: book.id }
attributes.merge did the trick.
I am using Rails 4, Ember 1.2.0 and Ember Data 1.0.0-beta.3 and DS.ActiveModelSerializer.
I have trouble saving a new record with a 'has many' relationship. Two model records should be created but only by one POST request.
I have 2 models which looks like this:
Lingohub.SupportCase = DS.Model.extend({
subject: DS.attr('string'),
status: DS.attr('string'),
created_at: DS.attr('date'),
supportCaseMessages: DS.hasMany('supportCaseMessage')
});
Lingohub.SupportCaseMessage = DS.Model.extend({
supportCase: DS.belongsTo('supportCase'),
text: DS.attr('string'),
created_at: DS.attr('date')
});
My NEW route creates support case and support case massage:
Lingohub.SupportCasesNewRoute = Ember.Route.extend({
model: function() {
var support_case = this.store.createRecord('supportCase');
support_case.get('supportCaseMessages').createRecord();
return support_case;
}
});
My new form looks like this: (I don't know if you can bind an child attribute easier?)
<form {{action 'create' this on="submit"}} id="new_support_case">
{{input value=subject}}
{{!-- {{supportCaseMessages.0.text}} --}}
{{#each supportCaseMessages}}
{{textarea value=text}}
{{/each}}
<input type="submit">
</form>
'create' action in the controller:
Lingohub.SupportCasesNewController = Ember.ObjectController.extend({
actions: {
create: function(supportCase) {
var message = supportCase.get('supportCaseMessages.content')[0];
console.log(message.get('text'))
supportCase.save();
}
}
});
The POST Request to the Server only sends the 'support case'!!
{"support_case"=>{"subject"=>"aaaaaa", "status"=>nil, "created_at"=>nil}}
How can I send the additional record 'support case message' and the relationship ?
I try to answer my own question. If I do the following I get "support_case_messages" embedded in "support_case", is this really the best way to send 'two models' in one POST request?
Lingohub.SupportCaseSerializer = DS.ActiveModelSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key, jsonKey;
key = relationship.key;
jsonKey = Ember.String.underscore(key);
json[jsonKey] = [];
record.get(key).forEach(function(item) {
return json[jsonKey].push(item);
});
console.log(json)
return json;
}
});
I'm looking at example of using hadlebars.js, where template processing looks like:
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = { users: [
{username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{username: "allison", firstName: "Allison", lastName: "House", email: "allison#test.com" },
{username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" }
]};
$("#content-placeholder").html(template(data));
and template is:
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
Now I have JSON result from ASP.NET MVC and I can't think the way I should descripbe my template, because it does not have "users" property, it looks like:
{[{username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" }]}
Can I somehow affect JsonResult to output what I need, or there is a way to fix template without touching the controller code?
In your controller replace:
return Json(users);
with:
return Json(new { users = users });
Alternatively, without introducing the anonymous object with the users property, you can change your template like so:
<tbody>
{{#each this}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>
I am trying to populate a ruby on rails select box from a database query, the data comes from 3 tables.
My query
#data = Session.all :include => { :term => :courses }
Object
!ruby/object:Session
attributes:
created_at: 2010-06-17 22:12:05
term_id: "15"
updated_at: 2010-06-17 22:12:05
id: "3"
course_id: "1"
attributes_cache: {}
term: &id003 !ruby/object:Term
attributes:
number: "1"
start_date: 2010-06-17
created_at: 2010-06-17 22:12:05
updated_at: 2010-06-17 22:12:05
id: "15"
attributes_cache: {}
courses:
- &id001 !ruby/object:Course
attributes:
created_at:
updated_at:
course_name: Beginner
id: "1"
date:
course_type: Programming
attributes_cache: {}
what i am trying to do is to have the term number followed by the data data and then the course
like this
1 01-09-10 Programming Beginners
The id for the option would be the session_id
any ideas ?
Thanks
Alex
in your erb template you can put the following code withing you form:
<%= select("session","id", #data.map{|d| ["#{d.term.number} #{d.term.start_date} #{d.course.course_type} #{d.course.course_name}",d.id]} %>